@interopio/browser 3.0.4 → 3.0.5
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.
- package/browser.d.ts +17 -2
- package/dist/browser.es.js +3 -3
- package/dist/browser.es.js.map +1 -1
- package/dist/browser.umd.js +3 -3
- package/dist/browser.umd.js.map +1 -1
- package/dist/browser.umd.min.js +1 -1
- package/package.json +5 -5
package/dist/browser.umd.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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,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 o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(n[i[o]]=e[i[o]])}return n}function t(e,t,n,i){return new(n||(n=Promise))((function(o,r){function s(e){try{c(i.next(e))}catch(e){r(e)}}function a(e){try{c(i.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))}const n={logger:"info",gateway:{webPlatform:{}},libraries:[],exposeAPI:!0};var i=function(e){return{ok:!0,result:e}},o=function(e){return{ok:!1,error:e}},r=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},s=function(e){if(!0===e.ok)return e.result;throw e.error},a=function(e,t){return!0===t.ok?i(e(t.result)):t},c=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:i(e(t.result,n.result))},u=function(e,t){return!0===t.ok?t:o(e(t.error))},d=function(e,t){return!0===t.ok?e(t.result):t},h=function(){return h=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},h.apply(this,arguments)};function l(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(!l(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(!l(e[i[n]],t[i[n]]))return!1}return!0}}var p=function(e){return Array.isArray(e)},f=function(e){return"object"==typeof e&&null!==e&&!p(e)},g=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)},m=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 o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(n[i[o]]=e[i[o]])}return n}(t,["at"]);return h({at:e+(n||"")},i)},y=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return u((function(t){return{kind:"DecoderError",input:e,at:"input"+(t.at||""),message:t.message||""}}),n.decode(e))},this.runPromise=function(e){return r(n.run(e))},this.runWithException=function(e){return s(n.run(e))},this.map=function(t){return new e((function(e){return a(t,n.decode(e))}))},this.andThen=function(t){return new e((function(e){return d((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?i(e):o({message:g("a string",e)})}))},e.number=function(){return new e((function(e){return"number"==typeof e?i(e):o({message:g("a number",e)})}))},e.boolean=function(){return new e((function(e){return"boolean"==typeof e?i(e):o({message:g("a boolean",e)})}))},e.constant=function(t){return new e((function(e){return l(e,t)?i(t):o({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})}))},e.object=function(t){return new e((function(e){if(f(e)&&t){var n={};for(var r in t)if(t.hasOwnProperty(r)){var s=t[r].decode(e[r]);if(!0!==s.ok)return void 0===e[r]?o({message:"the key '"+r+"' is required but was not present"}):o(v("."+r,s.error));void 0!==s.result&&(n[r]=s.result)}return i(n)}return f(e)?i(e):o({message:g("an object",e)})}))},e.array=function(t){return new e((function(e){if(p(e)&&t){return e.reduce((function(e,n,i){return c((function(e,t){return e.concat([t])}),e,function(e,n){return u((function(e){return v("["+n+"]",e)}),t.decode(e))}(n,i))}),i([]))}return p(e)?i(e):o({message:g("an array",e)})}))},e.tuple=function(t){return new e((function(e){if(p(e)){if(e.length!==t.length)return o({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var n=[],r=0;r<t.length;r++){var s=t[r].decode(e[r]);if(!s.ok)return o(v("["+r+"]",s.error));n[r]=s.result}return i(n)}return o({message:g("a tuple of length "+t.length,e)})}))},e.union=function(t,n){for(var i=[],o=2;o<arguments.length;o++)i[o-2]=arguments[o];return e.oneOf.apply(e,[t,n].concat(i))},e.intersection=function(t,n){for(var o=[],r=2;r<arguments.length;r++)o[r-2]=arguments[r];return new e((function(e){return[t,n].concat(o).reduce((function(t,n){return c(Object.assign,t,n.decode(e))}),i({}))}))},e.anyJson=function(){return new e((function(e){return i(e)}))},e.unknownJson=function(){return new e((function(e){return i(e)}))},e.dict=function(t){return new e((function(e){if(f(e)){var n={};for(var r in e)if(e.hasOwnProperty(r)){var s=t.decode(e[r]);if(!0!==s.ok)return o(v("."+r,s.error));n[r]=s.result}return i(n)}return o({message:g("an object",e)})}))},e.optional=function(t){return new e((function(e){return null==e?i(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 o({message:'expected a value matching one of the decoders, got the errors ["'+s+'"]'})}))},e.withDefault=function(t,n){return new e((function(e){return i(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 o({at:m(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!f(i))return o({at:m(t.slice(0,r+1)),message:g("an object",i)});if("number"==typeof t[r]&&!p(i))return o({at:m(t.slice(0,r+1)),message:g("an array",i)});i=i[t[r]]}return u((function(e){return void 0===i?{at:m(t),message:"path does not exist"}:v(m(t),e)}),n.decode(i))}))},e.succeed=function(t){return new e((function(e){return i(t)}))},e.fail=function(t){return new e((function(e){return o({message:t})}))},e.lazy=function(t){return new e((function(e){return t().decode(e)}))},e}(),b=y.string,w=y.number,I=y.boolean,C=y.anyJson;y.unknownJson;var S=y.constant,x=y.object,_=y.array;y.tuple,y.dict;var P=y.optional,T=y.oneOf;y.union,y.intersection,y.withDefault,y.valueAt,y.succeed,y.fail;var k=y.lazy;const M=b().where((e=>e.length>0),"Expected a non-empty string"),R=w().where((e=>e>=0),"Expected a non-negative number"),j=T(S("system"),S("windows"),S("appManager"),S("layouts"),S("intents"),S("notifications"),S("channels"),S("extension"),S("themes")),A=T(S("openWindow"),S("windowHello"),S("windowAdded"),S("windowRemoved"),S("getBounds"),S("getFrameBounds"),S("getUrl"),S("moveResize"),S("focus"),S("close"),S("getTitle"),S("setTitle"),S("focusChange")),E=T(S("appHello"),S("appDirectoryStateChange"),S("instanceStarted"),S("instanceStopped"),S("applicationStart"),S("instanceStop"),S("clear")),O=T(S("layoutAdded"),S("layoutChanged"),S("layoutRemoved"),S("get"),S("getAll"),S("export"),S("import"),S("remove"),S("clientSaveRequest"),S("getGlobalPermissionState"),S("checkGlobalActivated"),S("requestGlobalPermission"),S("getDefaultGlobal"),S("setDefaultGlobal"),S("clearDefaultGlobal")),N=T(S("raiseNotification"),S("requestPermission"),S("notificationShow"),S("notificationClick"),S("getPermission"),S("list"),S("notificationRaised"),S("notificationClosed"),S("click"),S("clear"),S("clearAll")),D=T(S("getEnvironment"),S("getBase"),S("platformShutdown")),W=T(S("top"),S("left"),S("right"),S("bottom")),L=x({top:w(),left:w(),width:R,height:R}),q=P(x({top:P(w()),left:P(w()),width:P(R),height:P(R),context:P(C()),relativeTo:P(M),relativeDirection:P(W),windowId:P(M),layoutComponentId:P(M)})),F=x({name:M,url:M,options:q}),G=x({windowId:P(M)}),U=x({windowId:M,name:M}),B=x({windowId:M}),$=x({windows:_(U),isWorkspaceFrame:I()}),J=x({windowId:M,title:b()}),H=x({windowId:M,hasFocus:I()}),K=x({windowId:M,top:P(w()),left:P(w()),width:P(R),height:P(R),relative:P(I())}),V=x({windowId:M,bounds:x({top:w(),left:w(),width:R,height:R})}),z=x({bounds:x({top:w(),left:w(),width:R,height:R})}),Q=x({windowId:M,url:M}),X=C(),Y=x({top:P(w()),left:P(w()),width:P(R),height:P(R)}),Z=x({id:M,applicationName:M}),ee=x({url:M,top:P(w()),left:P(w()),width:P(R),height:P(R)}),te=x({name:M,displayName:P(b()),contexts:P(_(b())),customConfig:P(x())}),ne=x({name:M,title:P(M),version:P(M),appId:P(M),manifest:M,manifestType:M,tooltip:P(M),description:P(M),contactEmail:P(M),supportEmail:P(M),publisher:P(M),images:P(_(x({url:P(M)}))),icons:P(_(x({icon:P(M)}))),customConfig:C(),intents:P(_(te))}),ie=x({name:M,type:M.where((e=>"window"===e),"Expected a value of window"),title:P(M),version:P(M),customProperties:P(C()),icon:P(b()),caption:P(b()),details:ee,intents:P(_(te)),hidden:P(I())}),oe=T(ie,ne);x({definitions:_(oe),mode:T(S("replace"),S("merge"))});const re=x({name:M}),se=x({definitions:_(ie)}),ae=x({name:M,type:M.where((e=>"window"===e),"Expected a value of window"),instances:_(Z),userProperties:P(C()),title:P(M),version:P(M),icon:P(M),caption:P(M)}),ce=x({name:M,type:M.where((e=>"window"===e),"Expected a value of window"),userProperties:C(),title:P(M),version:P(M),icon:P(M),caption:P(M)}),ue=x({appsAdded:_(ce),appsChanged:_(ce),appsRemoved:_(ce)}),de=x({apps:_(ae)}),he=x({id:M}),le=x({name:M,waitForAGMReady:I(),id:P(M),context:P(C()),top:P(w()),left:P(w()),width:P(R),height:P(R),relativeTo:P(M),relativeDirection:P(T(S("top"),S("left"),S("right"),S("bottom"))),forceChromeTab:P(I()),layoutComponentId:P(M)}),pe=T(S("Global"),S("Activity"),S("ApplicationDefault"),S("Swimlane"),S("Workspace")),fe=T(S("application"),S("activity")),ge=x({context:P(C()),bounds:L,createArgs:x({name:P(M),url:P(M),context:P(C())}),windowState:P(M),restoreState:P(M),instanceId:M,isCollapsed:P(I()),isSticky:P(I()),restoreSettings:x({groupId:P(M),groupZOrder:P(w())})}),me=x({type:S("window"),componentType:P(fe),application:M,state:ge}),ve=x({type:S("window"),config:x({appName:M,url:P(M),title:P(b()),allowExtract:P(I()),allowReorder:P(I()),showCloseButton:P(I()),isMaximized:P(I())})}),ye=x({type:S("group"),config:C(),children:_(T(ve))}),be=x({type:S("column"),config:C(),children:_(T(ye,ve,k((()=>be)),k((()=>we))))}),we=x({type:S("row"),config:C(),children:_(T(be,ye,ve,k((()=>we))))}),Ie=x({config:C(),context:C(),children:_(T(we,be,ye,ve))}),Ce=x({type:S("Workspace"),application:P(M),state:Ie}),Se=x({bounds:L,instanceId:M,selectedWorkspace:R,workspaces:_(Ie),windowState:P(M),restoreState:P(M),context:P(C())}),xe=x({type:S("workspaceFrame"),application:M,componentType:P(fe),state:Se}),_e=x({name:M,type:pe,components:_(T(me,Ce,xe)),context:P(C()),metadata:P(C()),version:P(w())}),Pe=x({name:M,context:P(C()),metadata:P(C()),instances:P(_(M)),ignoreInstances:P(_(M))}),Te=x({name:M,context:P(C()),closeRunningInstance:P(I()),closeMe:P(I()),timeout:P(R)}),ke=x({name:M,type:pe,context:P(C()),metadata:P(C())}),Me=x({name:M,type:pe}),Re=x({layout:Pe}),je=x({layout:Te}),Ae=x({type:pe}),Ee=x({layouts:_(_e)}),Oe=T(S("replace"),S("merge")),Ne=x({layouts:_(_e),mode:Oe,isManagerOperation:P(I())}),De=x({summaries:_(ke)}),We=x({layout:_e}),Le=x({layout:P(_e)}),qe=x({name:M}),Fe=T(S("findIntent"),S("getIntents"),S("raiseIntent"),S("raise")),Ge=x({applicationName:M,applicationTitle:b(),applicationDescription:P(b()),applicationIcon:P(b()),type:T(S("app"),S("instance")),displayName:P(b()),contextTypes:P(_(M)),instanceId:P(b()),instanceTitle:P(b()),resultType:P(b())});x({applicationName:b(),applicationIcon:P(b()),instanceId:P(b())});const Ue=x({intent:M,handler:Ge}),Be=x({name:M,handlers:_(Ge)}),$e=T(S("startNew"),S("reuse"),x({app:P(M),instance:P(M)})),Je=x({type:P(M),data:P(C())}),He=x({intents:_(Be)}),Ke=x({name:P(M),contextType:P(M),resultType:P(M)}),Ve=T(M,Ke),ze=x({filter:P(Ke)}),Qe=x({intent:M,target:P($e),context:P(Je),options:P(q),handlers:P(_(Ge)),timeout:P(R),waitUserResponseIndefinitely:P(I())}),Xe=T(M,Qe),Ye=x({enabled:I(),appName:M,waitResponseTimeout:w()}),Ze=x({intentRequest:Qe,resolverConfig:Ye}),et=x({request:Qe,handler:Ge,result:C()}),tt=x({intent:M,contextTypes:P(_(M)),displayName:P(b()),icon:P(b()),description:P(b()),resultType:P(b())}),nt=T(M,tt),it=e=>M.where((t=>e.includes(t)),"Expected a valid channel name"),ot=x({method:M,arguments:P(C()),target:P(T(S("all"),S("best")))}),rt=x({action:b(),title:M,icon:P(b()),interop:P(ot)}),st=x({badge:P(b()),body:P(b()),data:P(C()),dir:P(T(S("auto"),S("ltr"),S("rtl"))),icon:P(b()),image:P(b()),lang:P(b()),renotify:P(I()),requireInteraction:P(I()),silent:P(I()),tag:P(b()),timestamp:P(R),vibrate:P(_(w()))}),at=x({title:M,clickInterop:P(ot),actions:P(_(rt)),focusPlatformOnDefaultClick:P(I()),badge:P(b()),body:P(b()),data:P(C()),dir:P(T(S("auto"),S("ltr"),S("rtl"))),icon:P(b()),image:P(b()),lang:P(b()),renotify:P(I()),requireInteraction:P(I()),silent:P(I()),tag:P(b()),timestamp:P(R),vibrate:P(_(w())),severity:P(T(S("Low"),S("None"),S("Medium"),S("High"),S("Critical"))),showToast:P(I()),showInPanel:P(I())}),ct=x({name:M,meta:x({color:M}),data:P(x())}),ut=x({settings:at,id:M}),dt=x({settings:at}),ht=x({permissionGranted:I()}),lt=x({permission:T(S("default"),S("granted"),S("denied"))}),pt=x({definition:st,action:P(b()),id:P(M)}),ft=x({layoutType:T(S("Global"),S("Workspace")),layoutName:M,context:P(C())}),gt=x({windowContext:P(C())}),mt=x({state:T(S("prompt"),S("denied"),S("granted"))}),vt=x({isAvailable:I()}),yt=x({itemId:M}),bt=x({isSupported:I()}),wt=x({operation:M}),It=x({bounds:L}),Ct=x({displayName:M,name:M}),St=x({theme:Ct}),xt=x({themes:_(Ct)}),_t=x({name:M}),Pt=x({id:M,title:M,clickInterop:P(ot),actions:P(_(rt)),focusPlatformOnDefaultClick:P(I()),badge:P(b()),body:P(b()),data:P(C()),dir:P(T(S("auto"),S("ltr"),S("rtl"))),icon:P(b()),image:P(b()),lang:P(b()),renotify:P(I()),requireInteraction:P(I()),silent:P(I()),tag:P(b()),timestamp:P(R),vibrate:P(_(w())),severity:P(T(S("Low"),S("None"),S("Medium"),S("High"),S("Critical"))),showToast:P(I()),showInPanel:P(I())}),Tt=x({notification:Pt}),kt=x({notifications:_(Pt)}),Mt=x({id:M}),Rt={openWindow:{name:"openWindow",dataDecoder:F,resultDecoder:U},windowHello:{name:"windowHello",dataDecoder:G,resultDecoder:$},windowAdded:{name:"windowAdded",dataDecoder:U},windowRemoved:{name:"windowRemoved",dataDecoder:B},getBounds:{name:"getBounds",dataDecoder:B,resultDecoder:V},getFrameBounds:{name:"getFrameBounds",dataDecoder:B,resultDecoder:z},getUrl:{name:"getUrl",dataDecoder:B,resultDecoder:Q},moveResize:{name:"moveResize",dataDecoder:K},focus:{name:"focus",dataDecoder:B},close:{name:"close",dataDecoder:B},getTitle:{name:"getTitle",dataDecoder:B,resultDecoder:J},setTitle:{name:"setTitle",dataDecoder:J},focusChange:{name:"focusChange",dataDecoder:H}};function jt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function At(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 o=n instanceof Error?n:new Error(n);if(t)t(o);else{var r='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+o.stack;if(e)switch(e.errorHandling){case"log":return console.error(r);case"silent":return;case"throw":throw new Error(r)}console.error(r)}}return{add:function(e,t,o){var r=n[e];return r||(r=[],n[e]=r),r.push(t),o&&setTimeout((function(){o.forEach((function(o){var r;if(null===(r=n[e])||void 0===r?void 0:r.includes(t))try{Array.isArray(o)?t.apply(void 0,o):t.apply(void 0,[o])}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=[],o=1;o<arguments.length;o++)t[o-1]=arguments[o];var r=n[e];if(!r||0===r.length)return[];var s=[];return r.forEach((function(n){try{var o=n.apply(void 0,t);s.push(o)}catch(t){s.push(void 0),i(t,e)}})),s},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}At.default=At;var Et=At;class Ot{constructor(e,t,n){this._id=e,this._name=t,this._bridge=n,this.registry=Et(),this.myCtxKey=`___window___${this.id}`}get id(){return this._id.slice()}get name(){return this._name.slice()}clean(){this.ctxUnsubscribe&&this.ctxUnsubscribe()}processSelfFocusEvent(e){this.me.isFocused=e,this.registry.execute("focus-change",this.me)}toApi(){return t(this,void 0,void 0,(function*(){return this.ctxUnsubscribe=yield this._bridge.contextLib.subscribe(this.myCtxKey,(e=>this.registry.execute("context-updated",e))),this.me={id:this.id,name:this.name,isFocused:!1,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),onContextUpdated:this.onContextUpdated.bind(this),onFocusChanged:this.onFocusChanged.bind(this)},this.me}))}getURL(){return t(this,void 0,void 0,(function*(){return(yield this._bridge.send("windows",Rt.getUrl,{windowId:this.id})).url}))}onFocusChanged(e){if("function"!=typeof e)throw new Error("Cannot subscribe to context changes, because the provided callback is not a function!");return this.registry.add("focus-change",e)}moveResize(e){return t(this,void 0,void 0,(function*(){const t=Y.runWithException(e),n=Object.assign({},t,{windowId:this.id,relative:!1});return yield this._bridge.send("windows",Rt.moveResize,n),this.me}))}resizeTo(e,n){return t(this,void 0,void 0,(function*(){if(void 0===e&&void 0===n)return this.me;void 0!==e&&R.runWithException(e),void 0!==n&&R.runWithException(n);const t=Object.assign({},{width:e,height:n},{windowId:this.id,relative:!0});return yield this._bridge.send("windows",Rt.moveResize,t),this.me}))}moveTo(e,n){return t(this,void 0,void 0,(function*(){if(void 0===e&&void 0===n)return this.me;void 0!==e&&w().runWithException(e),void 0!==n&&w().runWithException(n);const t=Object.assign({},{top:e,left:n},{windowId:this.id,relative:!0});return yield this._bridge.send("windows",Rt.moveResize,t),this.me}))}focus(){return t(this,void 0,void 0,(function*(){return"Platform"===this.name?window.open(void 0,this.id):yield this._bridge.send("windows",Rt.focus,{windowId:this.id}),this.me}))}close(){return t(this,void 0,void 0,(function*(){return yield this._bridge.send("windows",Rt.close,{windowId:this.id}),this.me}))}getTitle(){return t(this,void 0,void 0,(function*(){return(yield this._bridge.send("windows",Rt.getTitle,{windowId:this.id})).title}))}setTitle(e){return t(this,void 0,void 0,(function*(){const t=M.runWithException(e);return yield this._bridge.send("windows",Rt.setTitle,{windowId:this.id,title:t}),this.me}))}getBounds(){return t(this,void 0,void 0,(function*(){return(yield this._bridge.send("windows",Rt.getBounds,{windowId:this.id})).bounds}))}getContext(){return t(this,void 0,void 0,(function*(){return yield this._bridge.contextLib.get(this.myCtxKey)}))}updateContext(e){return t(this,void 0,void 0,(function*(){const t=X.runWithException(e);return yield this._bridge.contextLib.update(this.myCtxKey,t),this.me}))}setContext(e){return t(this,void 0,void 0,(function*(){const t=X.runWithException(e);return yield this._bridge.contextLib.set(this.myCtxKey,t),this.me}))}onContextUpdated(e){if("function"!=typeof e)throw new Error("Cannot subscribe to context changes, because the provided callback is not a function!");return this.registry.add("context-updated",(t=>{e(t,this.me)}))}}const Nt={operationCheck:{name:"operationCheck",dataDecoder:wt,resultDecoder:bt},getWorkspaceWindowFrameBounds:{name:"getWorkspaceWindowFrameBounds",resultDecoder:It,dataDecoder:yt}},Dt=(e,t,n)=>new Promise(((i,o)=>{const r=setTimeout((()=>{o(n||`Promise timeout hit: ${t}`)}),t);new Promise(e).then((e=>{clearTimeout(r),i(e)})).catch((e=>{clearTimeout(r),o(e)}))}));class Wt{constructor(){this.registry=Et(),this.allWindowProjections=[]}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("windows.controller.web"),this.logger.trace("starting the web windows controller"),this.publicWindowId=n.publicWindowId,this.addWindowOperationExecutors(),this.ioc=n,this.bridge=n.bridge,this.instanceId=e.interop.instance.instance,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(),yield this.platformRegistration,yield this.initializeFocusTracking(),this.logger.trace("registration with the platform successful, attaching the windows property to glue and returning");const t=this.toApi();e.windows=t}))}handlePlatformShutdown(){this.registry.clear(),this.allWindowProjections=[],this.focusEventHandler&&(document.removeEventListener("visibilityChange",this.focusEventHandler),window.removeEventListener("focus",this.focusEventHandler),window.removeEventListener("blur",this.focusEventHandler))}handleBridgeMessage(e){return t(this,void 0,void 0,(function*(){yield this.platformRegistration;const t=A.runWithException(e.operation),n=Rt[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=n.dataDecoder.runWithException(e.data)),yield n.execute(i)}))}open(e,n,i){return t(this,void 0,void 0,(function*(){M.runWithException(e),M.runWithException(n);const t=q.runWithException(i),o=yield this.bridge.send("windows",Rt.openWindow,{name:e,url:n,options:t});return this.waitForWindowAdded(o.windowId)}))}list(){return this.allWindowProjections.map((e=>e.api))}findById(e){var t;return M.runWithException(e),null===(t=this.allWindowProjections.find((t=>t.id===e)))||void 0===t?void 0:t.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(){Rt.focusChange.execute=this.handleFocusChangeEvent.bind(this),Rt.windowAdded.execute=this.handleWindowAdded.bind(this),Rt.windowRemoved.execute=this.handleWindowRemoved.bind(this),Rt.getBounds.execute=this.handleGetBounds.bind(this),Rt.getFrameBounds.execute=this.handleGetBounds.bind(this),Rt.getTitle.execute=this.handleGetTitle.bind(this),Rt.getUrl.execute=this.handleGetUrl.bind(this),Rt.moveResize.execute=this.handleMoveResize.bind(this),Rt.setTitle.execute=this.handleSetTitle.bind(this)}my(){return Object.assign({},this.me)}onWindowAdded(e){if("function"!=typeof e)throw new Error("Cannot subscribe to window added, because the provided callback is not a function!");return this.registry.add("window-added",e)}onWindowRemoved(e){if("function"!=typeof e)throw new Error("Cannot subscribe to window removed, because the provided callback is not a function!");return this.registry.add("window-removed",e)}onWindowGotFocus(e){if("function"!=typeof e)throw new Error("Cannot subscribe to onWindowGotFocus, because the provided callback is not a function!");return this.registry.add("window-got-focus",e)}onWindowLostFocus(e){if("function"!=typeof e)throw new Error("Cannot subscribe to onWindowLostFocus, because the provided callback is not a function!");return this.registry.add("window-lost-focus",e)}sayHello(){return t(this,void 0,void 0,(function*(){return yield this.bridge.send("windows",Rt.windowHello,{windowId:this.publicWindowId})}))}registerWithPlatform(){return t(this,void 0,void 0,(function*(){const{windows:e,isWorkspaceFrame:t}=yield 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)throw new Error("Cannot initialize the window library, because I received no information about me from the platform");const n=yield this.ioc.buildWebWindow(this.publicWindowId,t.name);this.me=n.api,this.allWindowProjections.push(n)}const n=yield Promise.all(e.filter((e=>e.windowId!==this.publicWindowId)).map((e=>this.ioc.buildWebWindow(e.windowId,e.name))));this.logger.trace("all windows projections are completed, building the list collection"),this.allWindowProjections.push(...n)}))}handleFocusChangeEvent(e){return t(this,void 0,void 0,(function*(){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)}))}handleWindowAdded(e){return t(this,void 0,void 0,(function*(){if(this.allWindowProjections.some((t=>t.id===e.windowId)))return;const t=yield this.ioc.buildWebWindow(e.windowId,e.name);this.allWindowProjections.push(t),this.registry.execute("window-added",t.api)}))}handleWindowRemoved(e){return t(this,void 0,void 0,(function*(){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))}))}handleGetBounds(){return t(this,void 0,void 0,(function*(){if(!this.me&&!this.isWorkspaceFrame)throw new Error("This window cannot report it's bounds, because it is not a Glue Window, most likely because it is an iframe");return{windowId:this.isWorkspaceFrame?"noop":this.me.id,bounds:{top:window.screenTop,left:window.screenLeft,width:window.innerWidth,height:window.innerHeight}}}))}handleGetTitle(){return t(this,void 0,void 0,(function*(){if(!this.me)throw new Error("This window cannot report it's title, because it is not a Glue Window, most likely because it is an iframe");return{windowId:this.me.id,title:document.title}}))}handleGetUrl(){return t(this,void 0,void 0,(function*(){if(!this.me)throw new Error("This window cannot report it's url, because it is not a Glue Window, most likely because it is an iframe");return{windowId:this.me.id,url:window.location.href}}))}handleMoveResize(e){return t(this,void 0,void 0,(function*(){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,o="number"==typeof e.width?e.width:e.relative?0:window.innerWidth,r=e.relative?window.moveBy:window.moveTo,s=e.relative?window.resizeBy:window.resizeTo;r(n,t),s(o,i)}))}handleSetTitle(e){return t(this,void 0,void 0,(function*(){document.title=e.title}))}initializeFocusTracking(){return t(this,void 0,void 0,(function*(){if(this.isWorkspaceFrame)return void this.logger.trace("Ignoring the focus tracking, because this client is a workspace frame");try{yield this.bridge.send("windows",Nt.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();yield this.transmitFocusChange(!0),e||(yield 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):Dt((t=>{const n=this.onWindowAdded((i=>{i.id===e&&(n(),t(i))}))}),3e4,`Timed out waiting for ${e} to be announced`)}transmitFocusChange(e){var n;return t(this,void 0,void 0,(function*(){const t={windowId:(null===(n=this.me)||void 0===n?void 0:n.id)||`iframe-${this.instanceId}`,hasFocus:e};this.me&&(this.me.isFocused=e),yield this.bridge.send("windows",Rt.focusChange,t)}))}defineEventListeners(){this.focusEventHandler=this.processFocusEvent.bind(this),document.addEventListener("visibilityChange",this.focusEventHandler),window.addEventListener("focus",this.focusEventHandler),window.addEventListener("blur",this.focusEventHandler)}}const Lt="T42.Web.Platform.Control",qt="T42.Web.Platform.Stream",Ft="T42.Web.Client.Control",Gt="T42.Core.Plus.Themes.Stream";class Ut{constructor(e,t){this.coreGlue=e,this.communicationId=t,this.platformMethodTimeoutMs=1e4}get contextLib(){return this.coreGlue.contexts}get interopInstance(){return this.coreGlue.interop.instance.instance}stop(){return t(this,void 0,void 0,(function*(){this.running=!1,this.sub.close(),yield this.coreGlue.interop.unregister(Ft)}))}start(e){return t(this,void 0,void 0,(function*(){this.running=!0,this.controllers=e,yield Promise.all([this.checkWaitMethod(Lt),this.checkWaitMethod(qt)]);const t=this.communicationId,[n]=yield Promise.all([this.coreGlue.interop.subscribe(qt,t?{target:{instance:this.communicationId}}:void 0),this.coreGlue.interop.registerAsync(Ft,((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:null==t?void 0:t.application,applicationName:null==t?void 0:t.applicationName,peerId:null==t?void 0:t.peerId,instance:null==t?void 0:t.instance,windowId:null==t?void 0:t.windowId}}send(e,n,i,o,r){return t(this,void 0,void 0,(function*(){if(n.dataDecoder)try{n.dataDecoder.runWithException(i)}catch(e){throw new Error(`Unexpected Web->Platform outgoing validation error: ${e.message}, for operation: ${n.name} and input: ${JSON.stringify(e.input)}`)}if(!(!(null==r?void 0:r.includeOperationCheck)||(yield this.checkOperationSupported(e,n)).isSupported))throw new Error(`Cannot complete operation: ${n.name} for domain: ${e} because this client is connected to a platform which does not support it`);try{const t=yield this.transmitMessage(e,n,i,o);return n.resultDecoder&&n.resultDecoder.runWithException(t),t}catch(e){if(e.kind)throw new Error(`Unexpected Web<-Platform incoming validation error: ${e.message}, for operation: ${n.name} and input: ${JSON.stringify(e.input)}`);throw new Error(e.message)}}))}createNotificationsSteam(){return t(this,void 0,void 0,(function*(){if(!this.coreGlue.interop.methods().some((e=>e.name===Gt)))throw new Error("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.");return this.coreGlue.interop.subscribe(Gt,this.communicationId?{target:{instance:this.communicationId}}:void 0)}))}checkOperationSupported(e,n){return t(this,void 0,void 0,(function*(){try{return yield this.send(e,Nt.operationCheck,{operation:n.name})}catch(e){return{isSupported:!1}}}))}checkWaitMethod(e){return Dt((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 o=i.method,r=i.server,s=!this.communicationId||r.instance===this.communicationId;o.name===e&&s&&(n(),t())}))}),this.platformMethodTimeoutMs,`Cannot initiate Glue Web, because a system method's discovery timed out: ${e}`)}passMessageController(e,t,n){const i=j.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 o=i.result;this.controllers[o].handleBridgeMessage(e).then((e=>{t&&t(e)})).catch((e=>{n&&n(e),console.warn(e)}))}transmitMessage(e,n,i,o){return t(this,void 0,void 0,(function*(){const t={domain:e,data:i,operation:n.name};let r;const s=`Internal Platform Communication Error. Attempted operation: ${JSON.stringify(n.name)} with data: ${JSON.stringify(i)}. `,a=this.communicationId;try{if(!this.running)throw new Error("Cannot send a control message, because the platform shut down");if(r=yield this.coreGlue.interop.invoke(Lt,t,a?{instance:this.communicationId}:void 0,o),!r)throw new Error("Received unsupported result from the platform - empty result");if(!Array.isArray(r.all_return_values)||0===r.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(`${s} -> Inner message: ${t}`)}throw new Error(`${s} -> Inner message: ${e.message}`)}return r.all_return_values[0].returned}))}}const Bt={appHello:{name:"appHello",dataDecoder:G,resultDecoder:de},appDirectoryStateChange:{name:"appDirectoryStateChange",dataDecoder:ue},instanceStarted:{name:"instanceStarted",dataDecoder:Z},instanceStopped:{name:"instanceStopped",dataDecoder:Z},applicationStart:{name:"applicationStart",dataDecoder:le,resultDecoder:Z},instanceStop:{name:"instanceStop",dataDecoder:he},import:{name:"import"},remove:{name:"remove",dataDecoder:re},export:{name:"export",resultDecoder:se},clear:{name:"clear"}};class $t{constructor(){this.baseApplicationsTimeoutMS=6e4,this.appImportTimeoutMS=20,this.registry=Et(),this.applications=[],this.instances=[]}handlePlatformShutdown(){this.registry.clear(),this.applications=[],this.instances=[],delete this.me}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("appManger.controller.web"),this.logger.trace("starting the web appManager controller"),this.publicWindowId=n.publicWindowId,this.addOperationsExecutors(),this.ioc=n,this.bridge=n.bridge,this.platformRegistration=this.registerWithPlatform(),yield this.platformRegistration,this.logger.trace("registration with the platform successful, attaching the appManager property to glue and returning");const t=this.toApi();e.appManager=t}))}handleBridgeMessage(e){return t(this,void 0,void 0,(function*(){yield this.platformRegistration;const t=E.runWithException(e.operation),n=Bt[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=n.dataDecoder.runWithException(e.data)),yield n.execute(i)}))}onInstanceStarted(e){if("function"!=typeof e)throw new Error("onInstanceStarted requires a single argument of type function");return this.registry.add("instance-started",e,this.instances)}onInstanceStopped(e){if("function"!=typeof e)throw new Error("onInstanceStopped requires a single argument of type function");return this.registry.add("instance-stopped",e)}startApplication(e,n,i){var o;return t(this,void 0,void 0,(function*(){const t={name:e,waitForAGMReady:null===(o=null==i?void 0:i.waitForAGMReady)||void 0===o||o,context:n,top:null==i?void 0:i.top,left:null==i?void 0:i.left,width:null==i?void 0:i.width,height:null==i?void 0:i.height,relativeTo:null==i?void 0:i.relativeTo,relativeDirection:null==i?void 0:i.relativeDirection,id:null==i?void 0:i.reuseId,forceChromeTab:null==i?void 0:i.forceTab,layoutComponentId:null==i?void 0:i.layoutComponentId},r=yield this.bridge.send("appManager",Bt.applicationStart,t),s=this.applications.find((e=>e.name===r.applicationName));return this.ioc.buildInstance(r,s)}))}getApplication(e){const t=M.runWithException(e);return this.applications.find((e=>e.name===t))}getInstances(){return this.instances.slice()}toApi(){return{myInstance:this.me,inMemory:{import:this.import.bind(this),remove:this.remove.bind(this),export:this.export.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(){Bt.appDirectoryStateChange.execute=this.handleAppDirectoryStateChange.bind(this),Bt.instanceStarted.execute=this.handleInstanceStartedMessage.bind(this),Bt.instanceStopped.execute=this.handleInstanceStoppedMessage.bind(this)}handleAppDirectoryStateChange(e){return t(this,void 0,void 0,(function*(){e.appsAdded.forEach(this.handleApplicationAddedMessage.bind(this)),e.appsChanged.forEach(this.handleApplicationChangedMessage.bind(this)),e.appsRemoved.forEach(this.handleApplicationRemovedMessage.bind(this))}))}onAppAdded(e){if("function"!=typeof e)throw new Error("onAppAdded requires a single argument of type function");return this.registry.add("application-added",e,this.applications)}onAppRemoved(e){if("function"!=typeof e)throw new Error("onAppRemoved requires a single argument of type function");return this.registry.add("application-removed",e)}onAppChanged(e){if("function"!=typeof e)throw new Error("onAppChanged requires a single argument of type function");return this.registry.add("application-changed",e)}handleApplicationAddedMessage(e){return t(this,void 0,void 0,(function*(){if(this.applications.some((t=>t.name===e.name)))return;const t=yield 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)}))}handleApplicationRemovedMessage(e){return t(this,void 0,void 0,(function*(){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)}))}handleApplicationChangedMessage(e){return t(this,void 0,void 0,(function*(){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)}))}handleInstanceStartedMessage(e){return t(this,void 0,void 0,(function*(){if(this.instances.some((t=>t.id===e.id)))return;const t=this.applications.find((t=>t.name===e.applicationName));if(!t)throw new Error(`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)}))}handleInstanceStoppedMessage(e){return t(this,void 0,void 0,(function*(){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)}))}import(e,n="replace"){return t(this,void 0,void 0,(function*(){if(Oe.runWithException(n),!Array.isArray(e))throw new Error("Import must be called with an array of definitions");if(e.length>1e4)throw new Error("Cannot import more than 10000 app definitions in Glue42 Core.");const t=e.reduce(((e,t)=>{const n=oe.run(t);return n.ok?e.valid.push(t):e.invalid.push({app:null==t?void 0:t.name,error:JSON.stringify(n.error)}),e}),{valid:[],invalid:[]}),i=this.baseApplicationsTimeoutMS+this.appImportTimeoutMS*t.valid.length;return yield this.bridge.send("appManager",Bt.import,{definitions:t.valid,mode:n},{methodResponseTimeoutMs:i}),{imported:t.valid.map((e=>e.name)),errors:t.invalid}}))}remove(e){return t(this,void 0,void 0,(function*(){M.runWithException(e),yield this.bridge.send("appManager",Bt.remove,{name:e},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}))}clear(){return t(this,void 0,void 0,(function*(){yield this.bridge.send("appManager",Bt.clear,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}))}export(){return t(this,void 0,void 0,(function*(){return(yield this.bridge.send("appManager",Bt.export,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})).definitions}))}getApplications(){return this.applications.slice()}registerWithPlatform(){return t(this,void 0,void 0,(function*(){const e=yield this.bridge.send("appManager",Bt.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=yield 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`)}))}findMyInstance(){for(const e of this.applications){const t=e.instances.find((e=>e.id===this.publicWindowId));if(t)return t}}}class Jt{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}getContext(){return t(this,void 0,void 0,(function*(){return this.bridge.contextLib.get(this.myCtxKey)}))}stop(){return t(this,void 0,void 0,(function*(){yield this.bridge.send("appManager",Bt.instanceStop,{id:this.data.id})}))}}class Ht{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),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)};return this.me=e,this.me}onInstanceStarted(e){if("function"!=typeof e)throw new Error("OnInstanceStarted requires a single argument of type function");return this.controller.onInstanceStarted((t=>{t.application.name===this.data.name&&e(t)}))}onInstanceStopped(e){if("function"!=typeof e)throw new Error("OnInstanceStarted requires a single argument of type function");return this.controller.onInstanceStopped((t=>{t.application.name===this.data.name&&e(t)}))}start(e,n){return t(this,void 0,void 0,(function*(){return this.controller.startApplication(this.data.name,e,n)}))}}const Kt={layoutAdded:{name:"layoutAdded",dataDecoder:_e},layoutChanged:{name:"layoutChanged",dataDecoder:_e},layoutRemoved:{name:"layoutRemoved",dataDecoder:_e},get:{name:"get",dataDecoder:Me,resultDecoder:Le},getAll:{name:"getAll",dataDecoder:Ae,resultDecoder:De},export:{name:"export",dataDecoder:Ae,resultDecoder:Ee},import:{name:"import",dataDecoder:Ne},remove:{name:"remove",dataDecoder:Me},save:{name:"save",dataDecoder:Re,resultDecoder:We},restore:{name:"restore",dataDecoder:je},clientSaveRequest:{name:"clientSaveRequest",dataDecoder:ft,resultDecoder:gt},getGlobalPermissionState:{name:"getGlobalPermissionState",resultDecoder:mt},requestGlobalPermission:{name:"requestGlobalPermission",resultDecoder:vt},checkGlobalActivated:{name:"checkGlobalActivated",resultDecoder:vt},getDefaultGlobal:{name:"getDefaultGlobal",resultDecoder:Le},setDefaultGlobal:{name:"setDefaultGlobal",dataDecoder:qe},clearDefaultGlobal:{name:"clearDefaultGlobal"}};class Vt{constructor(){this.defaultLayoutRestoreTimeoutMS=12e4,this.registry=Et()}handlePlatformShutdown(){this.registry.clear()}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("layouts.controller.web"),this.logger.trace("starting the web layouts controller"),this.bridge=n.bridge,this.windowsController=n.windowsController,this.addOperationsExecutors();const t=this.toApi();this.logger.trace("no need for platform registration, attaching the layouts property to glue and returning"),e.layouts=t}))}handleBridgeMessage(e){return t(this,void 0,void 0,(function*(){const t=O.runWithException(e.operation),n=Kt[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=n.dataDecoder.runWithException(e.data)),yield n.execute(i)}))}toApi(){const e={get:this.get.bind(this),getAll:this.getAll.bind(this),export:this.export.bind(this),import:this.import.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),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)};return Object.freeze(e)}addOperationsExecutors(){Kt.layoutAdded.execute=this.handleOnAdded.bind(this),Kt.layoutChanged.execute=this.handleOnChanged.bind(this),Kt.layoutRemoved.execute=this.handleOnRemoved.bind(this),Kt.clientSaveRequest.execute=this.handleSaveRequest.bind(this)}get(e,n){return t(this,void 0,void 0,(function*(){M.runWithException(e),pe.runWithException(n);return(yield this.bridge.send("layouts",Kt.get,{name:e,type:n})).layout}))}getAll(e){return t(this,void 0,void 0,(function*(){pe.runWithException(e);return(yield this.bridge.send("layouts",Kt.getAll,{type:e})).summaries}))}export(e){return t(this,void 0,void 0,(function*(){pe.runWithException(e);return(yield this.bridge.send("layouts",Kt.export,{type:e})).layouts}))}import(e,n="replace"){return t(this,void 0,void 0,(function*(){if(Oe.runWithException(n),!Array.isArray(e))throw new Error("Import must be called with an array of layouts");if(e.length>1e3)throw new Error("Cannot import more than 1000 layouts at once in Glue42 Core.");const t=e.reduce(((e,t)=>{const n=_e.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=>t.valid.some((t=>t.name===e.name))));yield this.bridge.send("layouts",Kt.import,{layouts:i,mode:n})}))}save(e){return t(this,void 0,void 0,(function*(){Pe.runWithException(e);return(yield this.bridge.send("layouts",Kt.save,{layout:e})).layout}))}restore(e){return t(this,void 0,void 0,(function*(){Te.runWithException(e);const t=e.timeout?2*e.timeout:this.defaultLayoutRestoreTimeoutMS;yield this.bridge.send("layouts",Kt.restore,{layout:e},{methodResponseTimeoutMs:t})}))}remove(e,n){return t(this,void 0,void 0,(function*(){pe.runWithException(e),M.runWithException(n),yield this.bridge.send("layouts",Kt.remove,{type:e,name:n})}))}handleSaveRequest(e){return t(this,void 0,void 0,(function*(){const t={};if(this.saveRequestSubscription)try{const n=this.saveRequestSubscription(e);t.windowContext=null==n?void 0:n.windowContext}catch(e){this.logger.warn(`An error was thrown by the onSaveRequested callback, ignoring the callback: ${JSON.stringify(e)}`)}return t}))}getGlobalPermissionState(){return t(this,void 0,void 0,(function*(){return yield this.bridge.send("layouts",Kt.getGlobalPermissionState,void 0)}))}requestGlobalPermission(){return t(this,void 0,void 0,(function*(){const e=(yield 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)throw new Error("Cannot request permission for multi-window placement from any app other than the Platform.");return{permissionGranted:(yield this.bridge.send("layouts",Kt.requestGlobalPermission,void 0,{methodResponseTimeoutMs:18e4})).isAvailable}}))}checkGlobalActivated(){return t(this,void 0,void 0,(function*(){return{activated:(yield this.bridge.send("layouts",Kt.checkGlobalActivated,void 0)).isAvailable}}))}getDefaultGlobal(){return t(this,void 0,void 0,(function*(){return(yield this.bridge.send("layouts",Kt.getDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})).layout}))}setDefaultGlobal(e){return t(this,void 0,void 0,(function*(){M.runWithException(e),yield this.bridge.send("layouts",Kt.setDefaultGlobal,{name:e},void 0,{includeOperationCheck:!0})}))}clearDefaultGlobal(){return t(this,void 0,void 0,(function*(){yield this.bridge.send("layouts",Kt.clearDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})}))}onAdded(e){return this.export("Global").then((t=>t.forEach((t=>e(t))))).catch((()=>{})),this.export("Workspace").then((t=>t.forEach((t=>e(t))))).catch((()=>{})),this.registry.add(Kt.layoutAdded.name,e)}onChanged(e){return this.registry.add(Kt.layoutChanged.name,e)}onRemoved(e){return this.registry.add(Kt.layoutRemoved.name,e)}subscribeOnSaveRequested(e){if("function"!=typeof e)throw new Error("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function.");if(this.saveRequestSubscription)throw new Error("Cannot subscribe to onSaveRequested, because this client has already subscribed and only one subscription is supported. Consider unsubscribing from the initial one.");return this.saveRequestSubscription=e,()=>{delete this.saveRequestSubscription}}handleOnAdded(e){return t(this,void 0,void 0,(function*(){this.registry.execute(Kt.layoutAdded.name,e)}))}handleOnChanged(e){return t(this,void 0,void 0,(function*(){this.registry.execute(Kt.layoutChanged.name,e)}))}handleOnRemoved(e){return t(this,void 0,void 0,(function*(){this.registry.execute(Kt.layoutRemoved.name,e)}))}}const zt={raiseNotification:{name:"raiseNotification",dataDecoder:ut,resultDecoder:dt},requestPermission:{name:"requestPermission",resultDecoder:ht},notificationShow:{name:"notificationShow",dataDecoder:pt},notificationClick:{name:"notificationClick",dataDecoder:pt},getPermission:{name:"getPermission",resultDecoder:lt},list:{name:"list",resultDecoder:kt},notificationRaised:{name:"notificationRaised",dataDecoder:Tt},notificationClosed:{name:"notificationClosed",dataDecoder:Mt},click:{name:"click"},clear:{name:"clear"},clearAll:{name:"clearAll"}};var Qt={},Xt={get exports(){return Qt},set exports(e){Qt=e}},Yt={},Zt={get exports(){return Yt},set exports(e){Yt=e}},en=1;var tn,nn,on,rn={nextValue:function(){return(en=(9301*en+49297)%233280)/233280},seed:function(e){en=e}},sn="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";function an(){on=!1}function cn(e){if(e){if(e!==tn){if(e.length!==sn.length)throw new Error("Custom alphabet for shortid must be "+sn.length+" unique characters. You submitted "+e.length+" characters: "+e);var t=e.split("").filter((function(e,t,n){return t!==n.lastIndexOf(e)}));if(t.length)throw new Error("Custom alphabet for shortid must be "+sn.length+" unique characters. These characters were not unique: "+t.join(", "));tn=e,an()}}else tn!==sn&&(tn=sn,an())}function un(){return on||(on=function(){tn||cn(sn);for(var e,t=tn.split(""),n=[],i=rn.nextValue();t.length>0;)i=rn.nextValue(),e=Math.floor(i*t.length),n.push(t.splice(e,1)[0]);return n.join("")}())}var dn,hn={get:function(){return tn||sn},characters:function(e){return cn(e),tn},seed:function(e){rn.seed(e),nn!==e&&(an(),nn=e)},lookup:function(e){return un()[e]},shuffled:un},ln="object"==typeof window&&(window.crypto||window.msCrypto);dn=ln&&ln.getRandomValues?function(e){return ln.getRandomValues(new Uint8Array(e))}:function(e){for(var t=[],n=0;n<e;n++)t.push(Math.floor(256*Math.random()));return t};var pn=hn,fn=dn,gn=function(e,t,n){for(var i=(2<<Math.log(t.length-1)/Math.LN2)-1,o=-~(1.6*i*n/t.length),r="";;)for(var s=e(o),a=o;a--;)if((r+=t[s[a]&i]||"").length===+n)return r};var mn,vn,yn=function(e){for(var t,n=0,i="";!t;)i+=gn(fn,pn.get(),1),t=e<Math.pow(16,n+1),n++;return i},bn=yn,wn=1567752802062,In=7;var Cn=function(e){var t="",n=Math.floor(.001*(Date.now()-wn));return n===vn?mn++:(mn=0,vn=n),t+=bn(In),t+=bn(e),mn>0&&(t+=bn(mn)),t+=bn(n)},Sn=hn;var xn=function(e){return!(!e||"string"!=typeof e||e.length<6)&&!new RegExp("[^"+Sn.get().replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&")+"]").test(e)};!function(e){var t=hn,n=Cn,i=xn,o=0;function r(){return n(o)}e.exports=r,e.exports.generate=r,e.exports.seed=function(n){return t.seed(n),e.exports},e.exports.worker=function(t){return o=t,e.exports},e.exports.characters=function(e){return void 0!==e&&t.characters(e),t.shuffled()},e.exports.isValid=i}(Zt),function(e){e.exports=Yt}(Xt);var _n=jt(Qt);class Pn{constructor(){this.registry=Et(),this.notifications={}}handlePlatformShutdown(){this.notifications={},this.registry.clear()}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("notifications.controller.web"),this.logger.trace("starting the web notifications controller"),this.bridge=n.bridge,this.coreGlue=e,this.notificationsSettings=n.config.notifications,this.buildNotificationFunc=n.buildNotification;const t=this.toApi();this.addOperationExecutors(),e.notifications=t,this.logger.trace("notifications are ready")}))}handleBridgeMessage(e){return t(this,void 0,void 0,(function*(){const t=N.runWithException(e.operation),n=zt[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=n.dataDecoder.runWithException(e.data)),yield 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)};return Object.freeze(e)}getPermission(){return t(this,void 0,void 0,(function*(){return(yield this.bridge.send("notifications",zt.getPermission,void 0)).permission}))}requestPermission(){return t(this,void 0,void 0,(function*(){return(yield this.bridge.send("notifications",zt.requestPermission,void 0)).permissionGranted}))}raise(e){return t(this,void 0,void 0,(function*(){const t=at.runWithException(e);t.showToast="boolean"!=typeof t.showToast||t.showToast,t.showInPanel="boolean"!=typeof t.showInPanel||t.showInPanel;if(!(yield this.requestPermission()))throw new Error("Cannot raise the notification, because the user has declined the permission request");const n=Qt.generate(),i=yield this.bridge.send("notifications",zt.raiseNotification,{settings:t,id:n}),o=this.buildNotificationFunc(i.settings,n);return this.notifications[n]=o,o}))}list(){return t(this,void 0,void 0,(function*(){return(yield this.bridge.send("notifications",zt.list,void 0,void 0,{includeOperationCheck:!0})).notifications}))}onRaised(e){if("function"!=typeof e)throw new Error("onRaised expects a callback of type function");return this.registry.add("notification-raised",e)}onClosed(e){if("function"!=typeof e)throw new Error("onRaised expects a callback of type function");return this.registry.add("notification-closed",e)}click(e,n){return t(this,void 0,void 0,(function*(){M.runWithException(e),n&&M.runWithException(n),yield this.bridge.send("notifications",zt.click,{id:e,action:n},void 0,{includeOperationCheck:!0})}))}clear(e){return t(this,void 0,void 0,(function*(){M.runWithException(e),yield this.bridge.send("notifications",zt.clear,{id:e},void 0,{includeOperationCheck:!0})}))}clearAll(){return t(this,void 0,void 0,(function*(){yield this.bridge.send("notifications",zt.clearAll,void 0,void 0,{includeOperationCheck:!0})}))}addOperationExecutors(){zt.notificationShow.execute=this.handleNotificationShow.bind(this),zt.notificationClick.execute=this.handleNotificationClick.bind(this),zt.notificationRaised.execute=this.handleNotificationRaised.bind(this),zt.notificationClosed.execute=this.handleNotificationClosed.bind(this)}handleNotificationShow(e){return t(this,void 0,void 0,(function*(){if(!e.id)return;const t=this.notifications[e.id];t&&t.onshow&&t.onshow()}))}handleNotificationClick(e){var n,i,o,r,s;return t(this,void 0,void 0,(function*(){if(!e.action&&(null===(n=this.notificationsSettings)||void 0===n?void 0:n.defaultClick)&&this.notificationsSettings.defaultClick(this.coreGlue,e.definition),e.action&&(null===(o=null===(i=this.notificationsSettings)||void 0===i?void 0:i.actionClicks)||void 0===o?void 0:o.some((t=>t.action===e.action)))){(null===(s=null===(r=this.notificationsSettings)||void 0===r?void 0:r.actionClicks)||void 0===s?void 0:s.find((t=>t.action===e.action))).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])}))}handleNotificationRaised(e){return t(this,void 0,void 0,(function*(){this.registry.execute("notification-raised",e.notification)}))}handleNotificationClosed(e){return t(this,void 0,void 0,(function*(){this.registry.execute("notification-closed",e)}))}}const Tn={getIntents:{name:"getIntents",resultDecoder:He},findIntent:{name:"findIntent",dataDecoder:ze,resultDecoder:He},raiseIntent:{name:"raiseIntent",dataDecoder:Qe,resultDecoder:et},raise:{name:"raise",dataDecoder:Ze,resultDecoder:et}},kn=2147483647;class Mn{constructor(){this.myIntents=new Set,this.useIntentsResolverUI=!0,this.unregisterIntentPromises=[]}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("intents.controller.web"),this.logger.trace("starting the web intents controller"),this.bridge=n.bridge,this.interop=e.interop,this.legacyIntentsController=n.legacyIntentsHelper,this.checkIfIntentsResolverIsEnabled(n.config);const t=this.toApi();this.logger.trace("no need for platform registration, attaching the intents property to glue and returning"),e.intents=t}))}handlePlatformShutdown(){this.myIntents=new Set,this.unregisterIntentPromises=[]}handleBridgeMessage(e){return t(this,void 0,void 0,(function*(){const t=Fe.runWithException(e.operation),n=Tn[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=n.dataDecoder.runWithException(e.data)),yield 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)}}raise(e){return t(this,void 0,void 0,(function*(){const t=Xe.runWithException(e),n="string"==typeof t?{intent:t}:t;yield Promise.all(this.unregisterIntentPromises);const i=this.buildIntentRequestWithResolverInfo(n),o=yield this.isRaiseOperationSupported();if(!o.supported)return this.logger.warn(`${o.reason}. Invoking legacy raise method`),this.legacyIntentsController.raise(i,this.find.bind(this));this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(e)} and method response timeout of ${this.intentResolverResponseTimeout}ms`);const r=n.waitUserResponseIndefinitely?kn:(n.timeout||this.intentResolverResponseTimeout)+3e4;return yield this.bridge.send("intents",Tn.raise,i,{methodResponseTimeoutMs:r,waitTimeoutMs:r})}))}buildIntentRequestWithResolverInfo(e){return{intentRequest:e,resolverConfig:{enabled:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:e.waitUserResponseIndefinitely?kn:this.intentResolverResponseTimeout}}}isRaiseOperationSupported(){return t(this,void 0,void 0,(function*(){try{const{isSupported:e}=yield this.bridge.send("intents",Nt.operationCheck,{operation:"raise"});return{supported:e,reason:e?"":'The platform of this client is outdated and does not support "raise" operation'}}catch(e){return{supported:!1,reason:'The platform of this client is outdated and does not support "operationCheck" command'}}}))}all(){return t(this,void 0,void 0,(function*(){yield Promise.all(this.unregisterIntentPromises);return(yield this.bridge.send("intents",Tn.getIntents,void 0)).intents}))}addIntentListener(t,n){if(nt.runWithException(t),"function"!=typeof n)throw new Error("Cannot add intent listener, because the provided handler is not a function!");let i;const o="string"==typeof t?t:t.intent,r=this.buildInteropMethodName(o);if(this.myIntents.has(o))throw new Error(`Intent listener for intent ${o} already registered!`);this.myIntents.add(o);const s={unsubscribe:()=>{this.myIntents.delete(o),i.then((()=>this.interop.unregister(r))).catch((e=>this.logger.trace(`Unregistration of a method with name ${r} failed with reason: ${e}`)))}};let a={};if("object"==typeof t){a=e(t,["intent"])}return i=this.interop.register({name:r,flags:{intent:a}},(e=>{if(this.myIntents.has(o))return n(e)})),i.catch((e=>{this.myIntents.delete(o),this.logger.warn(`Registration of a method with name ${r} failed with reason: ${e}`)})),s}register(n,i){return t(this,void 0,void 0,(function*(){if(nt.runWithException(n),"function"!=typeof i)throw new Error("Cannot add intent listener, because the provided handler is not a function!");yield Promise.all(this.unregisterIntentPromises);const t="string"==typeof n?n:n.intent,o=this.buildInteropMethodName(t);if(this.myIntents.has(t))throw new Error(`Intent listener for intent ${t} already registered!`);this.myIntents.add(t);let r={};if("object"==typeof n){r=e(n,["intent"])}try{yield this.interop.register({name:o,flags:{intent:r}},(e=>{if(this.myIntents.has(t))return i(e)}))}catch(e){throw this.myIntents.delete(t),new Error(`Registration of a method with name ${o} failed with reason: ${JSON.stringify(e)}`)}return{unsubscribe:()=>this.unsubscribeIntent(t)}}))}find(e){return t(this,void 0,void 0,(function*(){let t;if(void 0!==e){const n=Ve.runWithException(e);"string"==typeof n?t={filter:{name:n}}:"object"==typeof n&&(t={filter:n})}yield Promise.all(this.unregisterIntentPromises);return(yield this.bridge.send("intents",Tn.findIntent,t)).intents}))}checkIfIntentsResolverIsEnabled(e){var t,n,i,o,r;this.useIntentsResolverUI="boolean"!=typeof(null===(t=e.intents)||void 0===t?void 0:t.enableIntentsResolverUI)||e.intents.enableIntentsResolverUI,this.intentsResolverAppName=null!==(i=null===(n=e.intents)||void 0===n?void 0:n.intentsResolverAppName)&&void 0!==i?i:"intentsResolver",this.intentResolverResponseTimeout=null!==(r=null===(o=e.intents)||void 0===o?void 0:o.methodResponseTimeoutMs)&&void 0!==r?r:6e4}clearUnregistrationPromise(e){this.unregisterIntentPromises=this.unregisterIntentPromises.filter((t=>t!==e))}buildInteropMethodName(e){return`Tick42.FDC3.Intents.${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)}))}}const Rn={name:"platformUnload"},jn={name:"transportSwitchRequest"},An={name:"transportSwitchResponse"},En={name:"getCurrentTransport"},On={name:"getCurrentTransportResponse"},Nn={name:"checkPreferredLogic"},Dn={name:"checkPreferredConnection"},Wn={name:"checkPreferredLogicResponse"},Ln={name:"checkPreferredConnectionResponse"},qn="web-platform",Fn="latest_fdc3_type",Gn={addChannel:{name:"addChannel",dataDecoder:ct}};class Un{constructor(){this.registry=Et(),this.GlueWebChannelsPrefix="___channel___",this.SubsKey="subs",this.ChangedKey="changed",this.replaySubscribe=(e,t)=>{this.get(t).then((t=>{if("object"==typeof t.data&&Object.keys(t.data).length){const n=this.createContextName(t.name);return this.contexts.subscribe(n,((t,n,i,o,r)=>{e(t.data,t,null==r?void 0:r.updaterId)}))}})).then((e=>{e&&"function"==typeof e&&e()})).catch((e=>this.logger.trace(e)))}}handlePlatformShutdown(){this.registry.clear()}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("channels.controller.web"),this.logger.trace("starting the web channels controller"),this.contexts=e.contexts,this.bridge=n.bridge,this.logger.trace("no need for platform registration, attaching the channels property to glue and returning");const t=this.toApi();e.channels=t}))}handleBridgeMessage(){return t(this,void 0,void 0,(function*(){}))}list(){return t(this,void 0,void 0,(function*(){const e=this.getAllChannelNames();return yield Promise.all(e.map((e=>this.get(e))))}))}my(){return this.current()}join(e){return t(this,void 0,void 0,(function*(){const t=this.getAllChannelNames();it(t).runWithException(e),yield this.switchToChannel(e)}))}onChanged(e){return this.changed(e)}leave(){return t(this,void 0,void 0,(function*(){yield this.switchToChannel()}))}toApi(){const e={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),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)};return Object.freeze(e)}createContextName(e){return`${this.GlueWebChannelsPrefix}${e}`}getAllChannelNames(){return this.contexts.all().filter((e=>e.startsWith(this.GlueWebChannelsPrefix))).map((e=>e.replace(this.GlueWebChannelsPrefix,"")))}unsubscribe(){this.unsubscribeFunc&&(this.unsubscribeFunc(),this.unsubscribeFunc=void 0)}switchToChannel(e){return t(this,void 0,void 0,(function*(){if(this.unsubscribe(),this.currentChannelName=e,void 0!==e){const t=this.createContextName(e);this.unsubscribeFunc=yield this.contexts.subscribe(t,((e,t,n,i,o)=>{this.registry.execute(this.SubsKey,e.data,e,null==o?void 0:o.updaterId)}))}this.registry.execute(this.ChangedKey,e)}))}updateData(e,n){return t(this,void 0,void 0,(function*(){const t=this.createContextName(e),i=this.getFDC3Type(n);if(this.contexts.setPathSupported){const e=Object.keys(n).map((e=>({path:`data.${e}`,value:n[e]})));i&&e.push({path:Fn,value:i}),yield this.contexts.setPaths(t,e)}else i&&(n[Fn]=i),yield this.contexts.update(t,{data:n})}))}getFDC3Type(e){const t=Object.keys(e).filter((e=>0===e.indexOf("fdc3_")));if(0!==t.length){if(t.length>1)throw new Error("FDC3 does not support updating of multiple context keys");return t[0].split("_").slice(1).join("_")}}subscribe(e){if("function"!=typeof e)throw new Error("Cannot subscribe to channels, because the provided callback is not a function!");const t=this.current();return t&&this.replaySubscribe(e,t),this.registry.add(this.SubsKey,e)}subscribeFor(e,n){return t(this,void 0,void 0,(function*(){const t=this.getAllChannelNames();if(it(t).runWithException(e),"function"!=typeof n)throw new Error(`Cannot subscribe to channel ${e}, because the provided callback is not a function!`);const i=this.createContextName(e);return this.contexts.subscribe(i,((e,t,i,o,r)=>{n(e.data,e,null==r?void 0:r.updaterId)}))}))}publish(e,t){if("object"!=typeof e)throw new Error("Cannot publish to channel, because the provided data is not an object!");if(void 0!==t){const n=this.getAllChannelNames();return it(n).runWithException(t),this.updateData(t,e)}if(void 0===this.currentChannelName)throw new Error("Cannot publish to channel, because not joined to a channel!");return this.updateData(this.currentChannelName,e)}all(){return t(this,void 0,void 0,(function*(){return this.getAllChannelNames()}))}get(n){return t(this,void 0,void 0,(function*(){const t=this.getAllChannelNames();it(t).runWithException(n);const i=this.createContextName(n),o=yield this.contexts.get(i);if(o.latest_fdc3_type){const t=e(o,["latest_fdc3_type"]);return Object.assign({},t)}return o}))}current(){return this.currentChannelName}changed(e){if("function"!=typeof e)throw new Error("Cannot subscribe to channel changed, because the provided callback is not a function!");return this.registry.add(this.ChangedKey,e)}add(e){return t(this,void 0,void 0,(function*(){const t=ct.runWithException(e);if(this.getAllChannelNames().includes(t.name))throw new Error("There's an already existing channel with such name");return yield this.bridge.send("channels",Gn.addChannel,t),t}))}}const Bn={getEnvironment:{name:"getEnvironment",resultDecoder:X},getBase:{name:"getBase",resultDecoder:X},platformShutdown:{name:"platformShutdown"}};class $n{start(e,n){return t(this,void 0,void 0,(function*(){this.bridge=n.bridge,this.ioc=n,this.addOperationsExecutors(),yield this.setEnvironment()}))}handleBridgeMessage(e){return t(this,void 0,void 0,(function*(){const t=D.runWithException(e.operation),n=Bn[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=n.dataDecoder.runWithException(e.data)),yield n.execute(i)}))}processPlatformShutdown(){return t(this,void 0,void 0,(function*(){Object.values(this.ioc.controllers).forEach((e=>e.handlePlatformShutdown?e.handlePlatformShutdown():null)),this.ioc.preferredConnectionController.stop(),this.ioc.eventsDispatcher.stop(),yield this.bridge.stop()}))}setEnvironment(){return t(this,void 0,void 0,(function*(){const e=yield this.bridge.send("system",Bn.getEnvironment,void 0),t=yield this.bridge.send("system",Bn.getBase,void 0),n=window.glue42core||window.iobrowser,i=window.glue42core?"glue42core":"iobrowser",o=Object.assign({},n,t,{environment:e});window[i]=Object.freeze(o)}))}addOperationsExecutors(){Bn.platformShutdown.execute=this.processPlatformShutdown.bind(this)}}class Jn{constructor(e,t){this.onclick=()=>{},this.onshow=()=>{},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}}T(S("clientHello"));const Hn={clientHello:{name:"clientHello",resultDecoder:x({widget:x({inject:I()})})}};class Kn{constructor(){this.channels=[],this.unsubFuncs=[],this.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=[]}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("extension.controller.web"),this.windowId=n.publicWindowId,this.logger.trace("starting the extension web controller"),this.bridge=n.bridge,this.channelsController=n.channelsController,this.eventsDispatcher=n.eventsDispatcher;try{yield this.registerWithPlatform()}catch(e){return}this.channels=yield this.channelsController.list();const t=this.eventsDispatcher.onContentMessage(this.handleContentMessage.bind(this)),i=this.channelsController.onChanged((e=>{this.eventsDispatcher.sendContentMessage({command:"channelChange",newChannel:e})}));this.unsubFuncs.push(t),this.unsubFuncs.push(i)}))}handleBridgeMessage(e){return t(this,void 0,void 0,(function*(){}))}handleContentMessage(e){if(!e||"string"!=typeof e.command)return;const t=this.contentCommands[e.command];t&&t.handle(e)}registerWithPlatform(){return t(this,void 0,void 0,(function*(){this.logger.trace("registering with the platform"),this.config=yield this.bridge.send("extension",Hn.clientHello,{windowId:this.windowId}),this.logger.trace("the platform responded to the hello message with a valid extension config")}))}handleWidgetVisualizationPermission(){var e;return t(this,void 0,void 0,(function*(){if(!(null===(e=this.config)||void 0===e?void 0:e.widget.inject))return this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!1});const t=this.channels.find((e=>e.name===this.channelsController.my()));this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!0,channels:this.channels,currentChannel:t})}))}handleChangeChannel(e){return t(this,void 0,void 0,(function*(){"no-channel"!==e.name?yield this.channelsController.join(e.name):yield this.channelsController.leave()}))}}class Vn{constructor(e){this.config=e,this.registry=Et(),this.glue42EventName="Glue42",this.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)}}}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)}wireCustomEventListener(){this._handleMessage=this.handleMessage.bind(this),window.addEventListener(this.glue42EventName,this._handleMessage)}handleMessage(e){var t;const n=e.detail,i=null!==(t=null==n?void 0:n.glue42)&&void 0!==t?t:null==n?void 0:n.glue42core;if(!i)return;const o=i.event,r=this.events[o];r&&r.handle(i.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)}send(e,t,n){const i={};i[t]={event:e,message:n};const o=new CustomEvent(this.glue42EventName,{detail:i});window.dispatchEvent(o)}}class zn{constructor(e){this.coreGlue=e,this.transactionTimeout=15e3,this.transactionLocks={},this.reconnectCounter=0,this.logger=this.coreGlue.logger.subLogger("web.preferred.connection.controller")}stop(){this.webPlatformMessagesUnsubscribe&&this.webPlatformMessagesUnsubscribe()}start(e){return t(this,void 0,void 0,(function*(){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()===qn))throw new Error("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=yield this.getCurrentPlatformTransportState();yield this.checkSwitchTransport(t)}))}handleWebPlatformMessage(e){if("string"==typeof e)return;const t=this.coreGlue.connection.transport.name()===qn,n=e.type,i=e.args,o=e.transactionId;return n===jn.name?this.handleTransportSwitchRequest(i,o):n!==Rn.name||t?n===On.name?this.handleGetCurrentTransportResponse(i,o):n===Nn.name?this.handleCheckPreferredLogic(o):n===Dn.name?this.handleCheckPreferredConnection(i,o):void 0:this.handlePlatformUnload()}reEstablishPlatformPort(){return t(this,void 0,void 0,(function*(){try{yield 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=yield this.getCurrentPlatformTransportState();yield this.checkSwitchTransport(e)}))}checkSwitchTransport(e){return t(this,void 0,void 0,(function*(){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=yield this.coreGlue.connection.switchTransport(e);this.setConnected(),this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(n)}`)}))}getCurrentPlatformTransportState(){return t(this,void 0,void 0,(function*(){this.logger.trace("Requesting the current transport state of the platform.");const e=this.setTransaction(En.name);this.sendPlatformMessage(En.name,e.id);const t=yield e.lock;return this.logger.trace(`The platform responded with transport state: ${JSON.stringify(t)}`),t}))}setTransaction(e){const t={},n=Qt.generate(),i=new Promise(((i,o)=>{let r=!0;t.lift=e=>{r=!1,delete this.transactionLocks[n],i(e)},t.fail=e=>{r=!1,delete this.transactionLocks[n],o(e)},setTimeout((()=>{r&&(r=!1,this.logger.warn(`Transaction for operation: ${e} timed out.`),delete this.transactionLocks[n],o(`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(An.name,t,{success:e.success})})).catch((e=>{this.logger.error(e),this.sendPlatformMessage(An.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];null==i||i.lift(n)}handleCheckPreferredLogic(e){setTimeout((()=>this.sendPlatformMessage(Wn.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(Ln.name,t,e)})).catch((e=>{this.logger.trace(`The connection to ${n} is not possible`),this.sendPlatformMessage(Ln.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()}}class Qn{constructor(e,t,n,i,o){this.bridge=t,this.interop=n,this.appManagerController=i,this.windowsController=o,this.intentsResolverResponsePromises={},this.logger=this.configureLogger(e)}raise(e,n){var i;return t(this,void 0,void 0,(function*(){const{intentRequest:t,resolverConfig:o}=e,r=(yield n(t.intent)).find((e=>e.name===t.intent));if(!r)throw new Error(`Intent with name ${t.intent} not found`);const{open:s,reason:a}=this.checkIfResolverShouldBeOpened(r,t,o);if(!s)return null===(i=this.logger)||void 0===i||i.trace(`Intent Resolver UI won't be used. Reason: ${a}`),this.invokeRaiseIntent(t);return yield this.raiseIntentWithResolverApp(e)}))}configureLogger(e){return e.subLogger("intents.legacy.helper.web")}raiseIntentWithResolverApp(e){return t(this,void 0,void 0,(function*(){const{intentRequest:t,resolverConfig:n}=e;this.logger.trace(`Intents Resolver UI with app name ${n.appName} will be used`);const i=yield this.registerResponseMethod();this.logger.trace(`Registered interop method ${i}`);const o=yield this.openIntentResolverApplication(e,i);this.logger.trace(`Intents Resolver Instance with id ${o.id} opened`);const r=yield this.handleInstanceResponse(o.id),s="app"===r.type?{app:r.applicationName}:{instance:r.instanceId};this.logger.trace(`Intent handler chosen by the user: ${JSON.stringify(s)}`);return yield this.invokeRaiseIntent(Object.assign(Object.assign({},t),{target:s}))}))}handleInstanceResponse(e){var n;return t(this,void 0,void 0,(function*(){try{const{handler:t,intent:i}=yield this.intentsResolverResponsePromises[e].promise;return null===(n=this.logger)||void 0===n||n.trace(`Intent handler chosen for intent ${i}: ${JSON.stringify(t)}`),this.stopResolverInstance(e),t}catch(t){throw this.stopResolverInstance(e),new Error(t)}}))}invokeRaiseIntent(e){return this.bridge.send("intents",Tn.raiseIntent,e)}registerResponseMethod(){return t(this,void 0,void 0,(function*(){const e="T42.Intents.Resolver.Control."+_n();return yield this.interop.register(e,this.resolverResponseHandler.bind(this)),e}))}openIntentResolverApplication(e,n){return t(this,void 0,void 0,(function*(){const{intentRequest:t,resolverConfig:i}=e,o=this.buildStartContext(t,n),r=yield this.buildStartOptions();this.logger.trace(`Starting Intents Resolver UI with context: ${JSON.stringify(o)} and options: ${r}`);const s=yield this.appManagerController.getApplication(i.appName).start(o,r);return this.logger.trace(`Intents Resolver instance with id ${s.id} opened`),this.subscribeOnInstanceStopped(s),this.createResponsePromise(t.intent,s.id,n,i.waitResponseTimeout),s}))}cleanUpIntentResolverPromise(e){return t(this,void 0,void 0,(function*(){const t=this.intentsResolverResponsePromises[e];if(!t)return;this.interop.unregister(t.methodName).catch((e=>this.logger.warn(e))),delete this.intentsResolverResponsePromises[e]}))}buildStartContext(e,t){return{intent:e,callerId:this.interop.instance.instance,methodName:t}}buildStartOptions(){return t(this,void 0,void 0,(function*(){const e=yield this.getTargetBounds();return{top:(e.height-440)/2+e.top,left:(e.width-400)/2+e.left,width:400,height:440}}))}getTargetBounds(){return t(this,void 0,void 0,(function*(){const e=(yield this.tryGetWindowBasedBounds())||(yield this.tryGetWorkspaceBasedBounds());if(e)return this.logger.trace(`Opening Intents Resolver UI with bounds: ${JSON.stringify(e)}`),e;const t={top:window.screen.availTop||0,left:window.screen.availLeft||0,width:window.screen.width,height:window.screen.height};return this.logger.trace(`Opening Intents Resolver UI relative to my screen bounds: ${JSON.stringify(t)}`),t}))}tryGetWindowBasedBounds(){return t(this,void 0,void 0,(function*(){try{const e=yield this.windowsController.my().getBounds();return this.logger.trace(`Opening the resolver UI relative to my window bounds: ${JSON.stringify(e)}`),e}catch(e){this.logger.trace(`Failure to get my window bounds: ${JSON.stringify(e)}`)}}))}tryGetWorkspaceBasedBounds(){return t(this,void 0,void 0,(function*(){try{yield this.bridge.send("workspaces",Nt.operationCheck,{operation:"getWorkspaceWindowFrameBounds"});const e=(yield this.bridge.send("workspaces",Nt.getWorkspaceWindowFrameBounds,{itemId:this.windowsController.my().id})).bounds;return this.logger.trace(`Opening the resolver UI relative to my workspace frame window bounds: ${JSON.stringify(e)}`),e}catch(e){this.logger.trace(`Failure to get my workspace frame window bounds: ${JSON.stringify(e)}`)}}))}subscribeOnInstanceStopped(e){const{application:t}=e,n=t.onInstanceStopped((i=>{if(i.id!==e.id)return;const o=this.intentsResolverResponsePromises[i.id];if(!o)return n();o.reject(`Cannot resolve raised intent "${o.intent}" - User closed ${t.name} app without choosing an intent handler`),this.cleanUpIntentResolverPromise(i.id),n()}))}createResponsePromise(e,t,n,i){let o=()=>{},r=()=>{};const s=Dt(((e,t)=>{o=e,r=t}),i,`Timeout of ${i}ms hit waiting for the user to choose a handler for intent ${e}`);this.intentsResolverResponsePromises[t]={intent:e,resolve:o,reject:r,promise:s,methodName:n}}resolverResponseHandler(e,t){const n=Ue.run(e),i=t.instance;if(n.ok)return this.logger.trace(`Intent Resolver instance with id ${i} send a valid response: ${JSON.stringify(n.result)}`),this.intentsResolverResponsePromises[i].resolve(n.result);this.logger.trace(`Intent Resolver instance with id ${i} sent an invalid response. Error: ${JSON.stringify(n.error)}`),this.intentsResolverResponsePromises[i].reject(n.error.message),this.stopResolverInstance(i)}stopResolverInstance(e){const t=this.appManagerController.getInstances().find((t=>t.id===e));t&&t.stop().catch((e=>this.logger.error(e)))}checkIfIntentHasMoreThanOneHandler(e,t){return"object"!=typeof t.target&&(t.handlers?t.handlers.length>1:e.handlers.length>1)}checkIfResolverShouldBeOpened(e,t,n){if(!n.enabled)return{open:!1,reason:"Intent Resolver is disabled. Raising intent to first found handler"};if(!this.appManagerController.getApplication(n.appName))return{open:!1,reason:`Application with name ${n.appName} not found`};return this.checkIfIntentHasMoreThanOneHandler(e,t)?{open:!0}:{open:!1,reason:"Raised intent has only one handler"}}}const Xn={getCurrent:{name:"getCurrent",resultDecoder:St},list:{name:"list",resultDecoder:xt},select:{name:"select",dataDecoder:_t}};class Yn{constructor(){this.registry=Et(),this.activeThemeSubs=0}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("themes.controller.web"),this.logger.trace("starting the web themes controller"),this.bridge=n.bridge;const t=this.toApi();e.themes=t,this.logger.trace("themes are ready")}))}handlePlatformShutdown(){var e;this.registry.clear(),this.activeThemeSubs=0,null===(e=this.themesSubscription)||void 0===e||e.close(),delete this.themesSubscription}handleBridgeMessage(){return t(this,void 0,void 0,(function*(){}))}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)}getCurrent(){return t(this,void 0,void 0,(function*(){return(yield this.bridge.send("themes",Xn.getCurrent,void 0,void 0,{includeOperationCheck:!0})).theme}))}list(){return t(this,void 0,void 0,(function*(){return(yield this.bridge.send("themes",Xn.list,void 0,void 0,{includeOperationCheck:!0})).themes}))}select(e){return t(this,void 0,void 0,(function*(){M.runWithException(e),yield this.bridge.send("themes",Xn.select,{name:e},void 0,{includeOperationCheck:!0})}))}onChanged(e){return t(this,void 0,void 0,(function*(){if("function"!=typeof e)throw new Error("onChanged requires a callback of type function");const t=this.themesSubscription?Promise.resolve():this.configureThemeSubscription();yield t,++this.activeThemeSubs;const n=this.registry.add("on-theme-change",e);return()=>this.themeUnsub(n)}))}configureThemeSubscription(){return t(this,void 0,void 0,(function*(){this.themesSubscription||(this.themesSubscription=yield this.bridge.createNotificationsSteam(),this.themesSubscription.onData((e=>{const t=e.data,n=St.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)})),this.themesSubscription.onClosed((()=>{this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"),this.registry.clear(),this.activeThemeSubs=0,delete this.themesSubscription})))}))}themeUnsub(e){var t;e(),--this.activeThemeSubs,this.activeThemeSubs||(null===(t=this.themesSubscription)||void 0===t||t.close(),delete this.themesSubscription)}}class Zn{constructor(){this.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}}get communicationId(){return this._communicationId}get publicWindowId(){return this._publicWindowId}get windowsController(){return this._windowsControllerInstance||(this._windowsControllerInstance=new Wt),this._windowsControllerInstance}get appManagerController(){return this._appManagerControllerInstance||(this._appManagerControllerInstance=new $t),this._appManagerControllerInstance}get layoutsController(){return this._layoutsControllerInstance||(this._layoutsControllerInstance=new Vt),this._layoutsControllerInstance}get themesController(){return this._themesControllerInstance||(this._themesControllerInstance=new Yn),this._themesControllerInstance}get notificationsController(){return this._notificationsControllerInstance||(this._notificationsControllerInstance=new Pn),this._notificationsControllerInstance}get intentsController(){return this._intentsControllerInstance||(this._intentsControllerInstance=new Mn),this._intentsControllerInstance}get legacyIntentsHelper(){return this._legacyIntentsHelperInstance||(this._legacyIntentsHelperInstance=new Qn(this._coreGlue.logger,this.bridge,this._coreGlue.interop,this.appManagerController,this.windowsController)),this._legacyIntentsHelperInstance}get systemController(){return this._systemControllerInstance||(this._systemControllerInstance=new $n),this._systemControllerInstance}get channelsController(){return this._channelsControllerInstance||(this._channelsControllerInstance=new Un),this._channelsControllerInstance}get extensionController(){return this._extensionController||(this._extensionController=new Kn),this._extensionController}get eventsDispatcher(){return this._eventsDispatcher||(this._eventsDispatcher=new Vn(this.config)),this._eventsDispatcher}get bridge(){return this._bridgeInstance||(this._bridgeInstance=new Ut(this._coreGlue,this.communicationId)),this._bridgeInstance}get preferredConnectionController(){return this._preferredConnectionController||(this._preferredConnectionController=new zn(this._coreGlue)),this._preferredConnectionController}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}buildWebWindow(e,n){return t(this,void 0,void 0,(function*(){const t=new Ot(e,n,this.bridge),i=yield t.toApi();return{id:e,model:t,api:i}}))}buildNotification(e,t){return new Jn(e,t)}buildApplication(e,n){return t(this,void 0,void 0,(function*(){const t=new Ht(e,[],this.appManagerController).toApi(),i=n.map((e=>this.buildInstance(e,t)));return t.instances.push(...i),t}))}buildInstance(e,t){return new Jt(e,this.bridge,t).toApi()}}var ei="3.0.4";var ti=function(e,t){return ti=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},ti(e,t)};function ni(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}ti(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var ii=function(){return ii=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},ii.apply(this,arguments)};function oi(e,t,n,i){return new(n||(n=Promise))((function(o,r){function s(e){try{c(i.next(e))}catch(e){r(e)}}function a(e){try{c(i.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))}function ri(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;r&&(r=0,a[0]&&(s=0)),s;)try{if(n=1,i&&(o=2&a[0]?i.return:a[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,a[1])).done)return o;switch(i=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,i=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],i=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function si(e,t,n){if(n||2===arguments.length)for(var i,o=0,r=t.length;o<r;o++)!i&&o in t||(i||(i=Array.prototype.slice.call(t,0,o)),i[o]=t[o]);return e.concat(i||Array.prototype.slice.call(t))}var ai={STRING:1,NUMBER:2,TIMESTAMP:3,OBJECT:4};function ci(e){return e.type===ai.TIMESTAMP?"timestamp":e.type===ai.NUMBER?"number":e.type===ai.STRING?"string":e.type===ai.OBJECT?"object":"unknown"}function ui(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function di(e){var t={},n=ci(e);if("object"===n){var i=Object.keys(e.value).reduce((function(t,n){var i=ui(e.value[n]);if("object"===i){var o=hi(e.value[n]);t[n]={type:"object",description:"",context:{},composite:o}}else t[n]={type:i,description:"",context:{}};return t}),{});t.composite=i}return t.name=li(e.path.join("/")+"/"+e.name),t.type=n,t.description=e.description,t.context={},t}function hi(e){return Object.keys(e).reduce((function(t,n){var i=ui(e[n]);return t[n]="object"===i?{type:"object",description:"",context:{},composite:hi(e[n])}:{type:i,description:"",context:{}},t}),{})}function li(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function pi(e){return"timestamp"===ci(e)?Date.now():fi(e.value)}function fi(e){return"object"!=typeof e?e:Object.keys(e).reduce((function(t,n){var i=e[n];return"object"==typeof i&&i.constructor!==Date?t[n]=fi(i):i.constructor===Date?t[n]=new Date(i).getTime():i.constructor===Boolean?t[n]=i.toString():t[n]=i,t}),{})}function gi(e){return e.reduce((function(e,t){return e.concat(Array.isArray(t)?gi(t):t)}),[])}function mi(e){var t=gi(e.root.getAggregateState()),n=t.sort((function(e,t){return e.state?t.state?t.state-e.state:-1:1}))[0],i=function(e){var t="";return e.forEach((function(e,n,i){var o=e.path.join(".");n===i.length-1?t+=o+"."+e.name+": "+e.description:t+=o+"."+e.name+": "+e.description+","})),t.length>100?t.slice(0,100)+"...":t}(t);return{description:i,value:n.state}}var vi={validate:function(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")}},yi=function(){function e(e,t,n,i,o){this.definition=e,this.system=t,this.transport=n,this.value=i,this.type=o,this.path=[],vi.validate(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)}return Object.defineProperty(e.prototype,"repo",{get:function(){var e;return null===(e=this.system)||void 0===e?void 0:e.repo},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"id",{get:function(){return"".concat(this.system.path,"/").concat(name)},enumerable:!1,configurable:!0}),e.prototype.update=function(e){return this.value=e,this.transport.updateMetric(this)},e}(),bi=function(e){function t(t,n,i,o){return e.call(this,t,n,i,o,ai.NUMBER)||this}return ni(t,e),t.prototype.incrementBy=function(e){this.update(this.value+e)},t.prototype.increment=function(){this.incrementBy(1)},t.prototype.decrement=function(){this.incrementBy(-1)},t.prototype.decrementBy=function(e){this.incrementBy(-1*e)},t}(yi),wi=function(e){function t(t,n,i,o){return e.call(this,t,n,i,o,ai.OBJECT)||this}return ni(t,e),t.prototype.update=function(e){return this.mergeValues(e),this.transport.updateMetric(this)},t.prototype.mergeValues=function(e){var t=this;return Object.keys(this.value).forEach((function(n){void 0!==e[n]&&(t.value[n]=e[n])}))},t}(yi),Ii=function(e){function t(t,n,i,o){return e.call(this,t,n,i,o,ai.STRING)||this}return ni(t,e),t}(yi),Ci=function(e){function t(t,n,i,o){return e.call(this,t,n,i,o,ai.TIMESTAMP)||this}return ni(t,e),t.prototype.now=function(){this.update(new Date)},t}(yi);function Si(e,t,n,i,o){if(!t)throw new Error("Repository is required");if(!n)throw new Error("Transport is required");var r,s,a=n,c=e,u=o||"",d=t,h=i,l=function e(t){if(!t||!t.parent)return[];var n=e(t.parent);return n.push(t.name),n}(i),p={},f=(s="/",((r=l)&&r.length>0?r.join(s):"")+e),g=t.root,m=[],v=[];function y(e,t,n,i){var o={name:""};o="string"==typeof e?{name:e}:e;var r=v.filter((function(e){return e.name===o.name}));if(r.length>0){var s=r[0];if(s.type!==t)throw new Error("A metric named ".concat(o.name," is already defined with different type."));return void 0!==n&&s.update(n).catch((function(){})),s}var a=i(o);return v.push(a),a}var b={get name(){return c},get description(){return u},get repo(){return d},get parent(){return h},path:l,id:f,root:g,get subSystems(){return m},get metrics(){return v},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");var n=m.filter((function(t){return t.name===e}));if(n.length>0)return n[0];var i=Si(e,d,a,b,t);return m.push(i),i},getState:function(){return p},setState:function(e,t){p={state:e,description:t},a.updateSystem(b,p)},stringMetric:function(e,t){return y(e,ai.STRING,t,(function(e){return new Ii(e,b,a,t)}))},timestampMetric:function(e,t){return y(e,ai.TIMESTAMP,t,(function(e){return new Ci(e,b,a,t)}))},objectMetric:function(e,t){return y(e,ai.OBJECT,t,(function(e){return new wi(e,b,a,t)}))},numberMetric:function(e,t){return y(e,ai.NUMBER,t,(function(e){return new bi(e,b,a,t)}))},getAggregateState:function(){var e=[];return Object.keys(p).length>0&&e.push({name:c,path:l,state:p.state,description:p.description}),m.forEach((function(t){var n=t.getAggregateState();n.length>0&&e.push.apply(e,n)})),e}};return a.createSystem(b),b}var xi=function(){function e(e,t){t.init(this),this.root=Si("",this,t),this.addSystemMetrics(this.root,e.clickStream||void 0===e.clickStream)}return e.prototype.addSystemMetrics=function(e,t){if("undefined"!=typeof navigator&&e.stringMetric("UserAgent",navigator.userAgent),t&&"undefined"!=typeof document){var n=e.subSystem("ClickStream"),i=function(e){var t;if(e.target){var i=e.target,o=i&&null!==(t=i.getAttribute("class"))&&void 0!==t?t:"";n.objectMetric("LastBrowserEvent",{type:"click",timestamp:new Date,target:{className:o,id:i.id,type:"<"+i.tagName.toLowerCase()+">",href:i.href||""}})}};n.objectMetric("Page",{title:document.title,page:window.location.href}),document.addEventListener?document.addEventListener("click",i):document.attachEvent("onclick",i)}e.stringMetric("StartTime",(new Date).toString());var o=e.stringMetric("StartURL",""),r=e.stringMetric("AppName","");if("undefined"!=typeof window){if(void 0!==window.location){var s=window.location.href;o.update(s)}void 0!==window.glue42gd&&r.update(window.glue42gd.appName)}},e}(),_i=function(){function e(){}return e.prototype.init=function(e){},e.prototype.createSystem=function(e){return Promise.resolve()},e.prototype.updateSystem=function(e,t){return Promise.resolve()},e.prototype.createMetric=function(e){return Promise.resolve()},e.prototype.updateMetric=function(e){return Promise.resolve()},e}(),Pi=function(){function e(e,t,n){this.api=e,this.lastCount=0,this.initialPublishTimeout=1e4,this.publishInterval=6e4,this.initialPublishTimeout=null!=t?t:this.initialPublishTimeout,this.publishInterval=null!=n?n:this.publishInterval,this.scheduleCollection(),this.system=this.api.subSystem("performance","Performance data published by the web application")}return e.prototype.scheduleCollection=function(){var e=this;setTimeout((function(){e.collect(),setInterval((function(){e.collect()}),e.publishInterval)}),this.initialPublishTimeout)},e.prototype.collect=function(){try{this.collectMemory(),this.collectEntries()}catch(e){}},e.prototype.collectMemory=function(){var e=window.performance.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}))},e.prototype.collectEntries=function(){var e=window.performance.getEntries();if(!(e.length<=this.lastCount)){this.lastCount=e.length;var t=e.map((function(e){return e.toJSON()}));this.system.stringMetric("entries",JSON.stringify(t))}},e}(),Ti=function(e){var t;t=e.connection&&"object"==typeof e.connection?function(e,t){var n,i,o=this;if(!e||"object"!=typeof e)throw new Error("Connection is required parameter");var r=function(e){s(e.root)},s=function(e){a(e),e.metrics.forEach((function(e){c(e)})),e.subSystems.forEach((function(e){s(e)}))},a=function(e){return oi(o,void 0,void 0,(function(){var t,o;return ri(this,(function(r){switch(r.label){case 0:return void 0===e.parent?[2]:[4,n];case 1:return r.sent(),t={name:li(e.path.join("/")+"/"+e.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}},o={type:"define",metrics:[t]},i.send(o),[2]}}))}))},c=function(e){return oi(o,void 0,void 0,(function(){var t,o,r;return ri(this,(function(s){switch(s.label){case 0:return t=d(e),[4,n];case 1:return s.sent(),o=di(t),r={type:"define",metrics:[o]},i.send(r),void 0!==t.value&&u(t),[2]}}))}))},u=function(e){if(h()){var t=pi(e),n={type:"publish",values:[{name:li(e.path.join("/")+"/"+e.name),value:t,timestamp:Date.now()}]};return i.sendFireAndForget(n)}return Promise.resolve()},d=function(e){var t=ii({},e);return"object"==typeof e.value&&null!==e.value&&(t.value=ii({},e.value)),t},h=function(){var e;try{return(null!==(e=t.canUpdateMetric)&&void 0!==e?e:function(){return!0})()}catch(e){return!0}};return{init:function(o){var s;n=new Promise((function(e){s=e})),(i=e.domain("metrics")).onJoined((function(e){!e&&s&&(s(),s=void 0);var t={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};i.send(t),e&&r(o)})),i.join({system:t.system,service:t.service,instance:t.instance})},createSystem:a,updateSystem:function(t,r){return oi(o,void 0,void 0,(function(){var o,s,a;return ri(this,(function(c){switch(c.label){case 0:return[4,n];case 1:return c.sent(),o={type:"publish",values:[{name:li(t.path.join("/")+"/"+t.name+"/State"),value:{Description:r.description,Value:r.state},timestamp:Date.now()}]},i.send(o),s=mi(t),a={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:s.description,Value:s.value},timestamp:Date.now()}]},i.send(a),[2]}}))}))},createMetric:c,updateMetric:function(e){return oi(o,void 0,void 0,(function(){var t;return ri(this,(function(i){switch(i.label){case 0:return t=d(e),[4,n];case 1:return i.sent(),u(t),[2]}}))}))}}}(e.connection,e):new _i;var n=new xi(e,t).root;e.disableAutoAppSystem||(n=n.subSystem("App"));var i=function(e){var t,n=e.subSystem("reporting"),i={name:"features"},o=function(e,o,r){if(void 0===e||""===e)throw new Error("name is mandatory");if(void 0===o||""===o)throw new Error("action is mandatory");if(void 0===r||""===r)throw new Error("payload is mandatory");t?t.update({name:e,action:o,payload:r}):t=n.objectMetric(i,{name:e,action:o,payload:r})};return e.featureMetric=o,e}(n);return function(e,t){var n,i;if("undefined"==typeof window)return;var o=null===(i=null===(n=null===window||void 0===window?void 0:window.glue42gd)||void 0===n?void 0:n.metrics)||void 0===i?void 0:i.pagePerformanceMetrics;o&&(t=o);(null==t?void 0:t.enabled)&&new Pi(e,t.initialPublishTimeout,t.publishInterval)}(i,e.pagePerformanceMetrics),i};var ki="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Mi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Ri(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 o=n instanceof Error?n:new Error(n);if(t)t(o);else{var r='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+o.stack;if(e)switch(e.errorHandling){case"log":return console.error(r);case"silent":return;case"throw":throw new Error(r)}console.error(r)}}return{add:function(e,t,o){var r=n[e];return r||(r=[],n[e]=r),r.push(t),o&&setTimeout((function(){o.forEach((function(o){var r;if(null===(r=n[e])||void 0===r?void 0:r.includes(t))try{Array.isArray(o)?t.apply(void 0,o):t.apply(void 0,[o])}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=[],o=1;o<arguments.length;o++)t[o-1]=arguments[o];var r=n[e];if(!r||0===r.length)return[];var s=[];return r.forEach((function(n){try{var o=n.apply(void 0,t);s.push(o)}catch(t){s.push(void 0),i(t,e)}})),s},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}Ri.default=Ri;var ji=Ri,Ai=function(){function e(e,t){var n=this;this.registry=ji(),this.gw=e.facade,this.gw.connect((function(e,t){n.messageHandler(t)})).then((function(e){n.client=e}))}return Object.defineProperty(e.prototype,"isObjectBasedTransport",{get:function(){return!0},enumerable:!1,configurable:!0}),e.prototype.sendObject=function(e){return this.client?(this.client.send(e),Promise.resolve(void 0)):Promise.reject("not connected")},e.prototype.send=function(e){return Promise.reject("not supported")},e.prototype.onMessage=function(e){return this.registry.add("onMessage",e)},e.prototype.onConnectedChanged=function(e){return e(!0),function(){}},e.prototype.close=function(){return Promise.resolve()},e.prototype.open=function(){return Promise.resolve()},e.prototype.name=function(){return"in-memory"},e.prototype.reconnect=function(){return Promise.resolve()},e.prototype.messageHandler=function(e){this.registry.execute("onMessage",e)},e}(),Ei=function(){function e(e,t){var n=this;this.logger=t,this.registry=ji(),this.worker=new SharedWorker(e),this.worker.port.onmessage=function(e){n.messageHandler(e.data)}}return Object.defineProperty(e.prototype,"isObjectBasedTransport",{get:function(){return!0},enumerable:!1,configurable:!0}),e.prototype.sendObject=function(e){return this.worker.port.postMessage(e),Promise.resolve()},e.prototype.send=function(e){return Promise.reject("not supported")},e.prototype.onMessage=function(e){return this.registry.add("onMessage",e)},e.prototype.onConnectedChanged=function(e){return e(!0),function(){}},e.prototype.close=function(){return Promise.resolve()},e.prototype.open=function(){return Promise.resolve()},e.prototype.name=function(){return"shared-worker"},e.prototype.reconnect=function(){return Promise.resolve()},e.prototype.messageHandler=function(e){this.registry.execute("onMessage",e)},e}(),Oi=function(){function e(){}return e.isNode=function(){if(void 0!==e._isNode)return e._isNode;if("undefined"!=typeof window)return e._isNode=!1,!1;try{e._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(t){e._isNode=!1}return e._isNode},e}(),Ni=function(){function e(){var e=this;this.rejected=!1,this.resolved=!1,this.promise=new Promise((function(t,n){e.resolve=function(n){e.resolved=!0,t(n)},e.reject=function(t){e.rejected=!0,n(t)}}))}return e.delay=function(e){return new Promise((function(t){return setTimeout(t,e)}))},Object.defineProperty(e.prototype,"ended",{get:function(){return this.rejected||this.resolved},enumerable:!1,configurable:!0}),e}(),Di={};function Wi(e){var t=Di[e];if(t)return t;var n=[];function i(){return(new Date).getTime()}var o,r,s=i();function a(e,t){var o=null!=t?t:i(),r=0;n.length>0&&(r=o-n[n.length-1].time),n.push({name:e,time:o,diff:r})}a("start",s);var c={get startTime(){return s},get endTime(){return o},get period(){return r},stop:function(){return a("end",o=i()),r=o-s},mark:a,marks:n};return Di[e]=c,c}var Li=Oi.isNode()?require("ws"):window.WebSocket,qi=function(){function e(e,t){if(this.startupTimer=Wi("connection"),this._running=!0,this._registry=ji(),this.wsRequests=[],this.settings=e,this.logger=t,!this.settings.ws)throw new Error("ws is missing")}return e.prototype.onMessage=function(e){return this._registry.add("onMessage",e)},e.prototype.send=function(e,t){var n=this;return new Promise((function(t,i){n.waitForSocketConnection((function(){var o;try{null===(o=n.ws)||void 0===o||o.send(e),t()}catch(e){i(e)}}),i)}))},e.prototype.open=function(){var e=this;return this.logger.info("opening ws..."),this._running=!0,new Promise((function(t,n){e.waitForSocketConnection(t,n)}))},e.prototype.close=function(){return this._running=!1,this.ws&&this.ws.close(),Promise.resolve()},e.prototype.onConnectedChanged=function(e){return this._registry.add("onConnectedChanged",e)},e.prototype.name=function(){return this.settings.ws},e.prototype.reconnect=function(){var e;null===(e=this.ws)||void 0===e||e.close();var t=new Ni;return this.waitForSocketConnection((function(){t.resolve()})),t.promise},e.prototype.waitForSocketConnection=function(e,t){var n;t=null!=t?t:function(){},this._running?1!==(null===(n=this.ws)||void 0===n?void 0:n.readyState)?(this.wsRequests.push({callback:e,failed:t}),this.wsRequests.length>1||this.openSocket()):e():t("wait for socket on ".concat(this.settings.ws," failed - socket closed by user"))},e.prototype.openSocket=function(e,t){return oi(this,void 0,void 0,(function(){var n=this;return ri(this,(function(i){switch(i.label){case 0:if(this.startupTimer.mark("opening-socket"),void 0===e&&(e=this.settings.reconnectInterval),void 0===t&&(t=this.settings.reconnectAttempts),void 0!==t){if(0===t)return this.notifyForSocketState("wait for socket on ".concat(this.settings.ws," failed - no more retries left")),[2];this.logger.debug("will retry ".concat(t," more times (every ").concat(e," ms)"))}i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.initiateSocket()];case 2:return i.sent(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState(),[3,4];case 3:return i.sent(),setTimeout((function(){var i=void 0===t?void 0:t-1;n.openSocket(e,i)}),e),[3,4];case 4:return[2]}}))}))},e.prototype.initiateSocket=function(){var e=this,t=new Ni;return this.logger.debug("initiating ws to ".concat(this.settings.ws,"...")),this.ws=new Li(this.settings.ws||""),this.ws.onerror=function(n){var i="";try{i=JSON.stringify(n)}catch(e){var o=new WeakSet;i=JSON.stringify(n,(function(e,t){if("object"==typeof t&&null!==t){if(o.has(t))return;o.add(t)}return t}))}t.reject("error"),e.notifyStatusChanged(!1,i)},this.ws.onclose=function(n){e.logger.info("ws closed ".concat(n)),t.reject("closed"),e.notifyStatusChanged(!1)},this.ws.onopen=function(){var n;e.startupTimer.mark("ws-opened"),e.logger.info("ws opened ".concat(null===(n=e.settings.identity)||void 0===n?void 0:n.application)),t.resolve(),e.notifyStatusChanged(!0)},this.ws.onmessage=function(t){e._registry.execute("onMessage",t.data)},t.promise},e.prototype.notifyForSocketState=function(e){this.wsRequests.forEach((function(t){e?t.failed&&t.failed(e):t.callback()})),this.wsRequests=[]},e.prototype.notifyStatusChanged=function(e,t){this._registry.execute("onConnectedChanged",e,t)},e}(),Fi={},Gi={get exports(){return Fi},set exports(e){Fi=e}},Ui={},Bi={get exports(){return Ui},set exports(e){Ui=e}},$i=1;var Ji,Hi,Ki,Vi={nextValue:function(){return($i=(9301*$i+49297)%233280)/233280},seed:function(e){$i=e}},zi="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";function Qi(){Ki=!1}function Xi(e){if(e){if(e!==Ji){if(e.length!==zi.length)throw new Error("Custom alphabet for shortid must be "+zi.length+" unique characters. You submitted "+e.length+" characters: "+e);var t=e.split("").filter((function(e,t,n){return t!==n.lastIndexOf(e)}));if(t.length)throw new Error("Custom alphabet for shortid must be "+zi.length+" unique characters. These characters were not unique: "+t.join(", "));Ji=e,Qi()}}else Ji!==zi&&(Ji=zi,Qi())}function Yi(){return Ki||(Ki=function(){Ji||Xi(zi);for(var e,t=Ji.split(""),n=[],i=Vi.nextValue();t.length>0;)i=Vi.nextValue(),e=Math.floor(i*t.length),n.push(t.splice(e,1)[0]);return n.join("")}())}var Zi,eo={get:function(){return Ji||zi},characters:function(e){return Xi(e),Ji},seed:function(e){Vi.seed(e),Hi!==e&&(Qi(),Hi=e)},lookup:function(e){return Yi()[e]},shuffled:Yi},to="object"==typeof window&&(window.crypto||window.msCrypto);Zi=to&&to.getRandomValues?function(e){return to.getRandomValues(new Uint8Array(e))}:function(e){for(var t=[],n=0;n<e;n++)t.push(Math.floor(256*Math.random()));return t};var no=eo,io=Zi,oo=function(e,t,n){for(var i=(2<<Math.log(t.length-1)/Math.LN2)-1,o=-~(1.6*i*n/t.length),r="";;)for(var s=e(o),a=o;a--;)if((r+=t[s[a]&i]||"").length===+n)return r};var ro,so,ao=function(e){for(var t,n=0,i="";!t;)i+=oo(io,no.get(),1),t=e<Math.pow(16,n+1),n++;return i},co=ao,uo=1567752802062,ho=7;var lo=function(e){var t="",n=Math.floor(.001*(Date.now()-uo));return n===so?ro++:(ro=0,so=n),t+=co(ho),t+=co(e),ro>0&&(t+=co(ro)),t+=co(n)},po=eo;var fo=function(e){return!(!e||"string"!=typeof e||e.length<6)&&!new RegExp("[^"+po.get().replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&")+"]").test(e)};!function(e){var t=eo,n=lo,i=fo,o=0;function r(){return n(o)}e.exports=r,e.exports.generate=r,e.exports.seed=function(n){return t.seed(n),e.exports},e.exports.worker=function(t){return o=t,e.exports},e.exports.characters=function(e){return void 0!==e&&t.characters(e),t.shuffled()},e.exports.isValid=i}(Bi),function(e){e.exports=Ui}(Gi);var go=Mi(Fi);function mo(e,t,n,i,o){null==e&&(e="global"),i=i||["success"],o=o||["error"];var r,s=!1,a=!1,c=!1,u=ji();t.disconnected((function(){c=!1,n.debug("connection is down"),s=!1,a=!0,u.execute("onLeft",{disconnected:!0})})),t.loggedIn((function(){c=!0,a&&(n.debug("connection is now up - trying to reconnect..."),h(r))})),t.on("success",(function(e){return p(e)})),t.on("error",(function(e){return l(e)})),t.on("result",(function(e){return p(e)})),i&&i.forEach((function(e){t.on(e,(function(e){return p(e)}))})),o&&o.forEach((function(e){t.on(e,(function(e){return l(e)}))}));var d={};function h(t){return r=t,new Promise((function(i,o){if(s)i({});else{var r;if("global"===e)r=c?Promise.resolve({}):Promise.reject("not connected to gateway");else n.debug("joining domain ".concat(e)),r=g({type:"join",destination:e,domain:"global",options:t});r.then((function(){!function(){n.debug("did join "+e),s=!0;var t=a;a=!1,u.execute("onJoined",t)}(),i({})})).catch((function(t){n.debug("error joining "+e+" domain: "+JSON.stringify(t)),o(t)}))}}))}function l(t){if(e===t.domain){var n=t.request_id;if(n){var i=d[n];i&&i.error(t)}}}function p(t){if(t.domain===e){var n=t.request_id;if(n){var i=d[n];i&&i.success(t)}}}function f(){return go()}function g(i,o,r){r=r||{},i.request_id=i.request_id||f(),i.domain=i.domain||e,r.skipPeerId||(i.peer_id=t.peerId);var s=i.request_id;return new Promise((function(e,a){d[s]={success:function(t){delete d[s],t._tag=o,e(t)},error:function(e){n.warn("GW error - ".concat(JSON.stringify(e)," for request ").concat(JSON.stringify(i))),delete d[s],e._tag=o,a(e)}},t.send(i,r).catch((function(e){d[s].error({err:e})}))}))}return{join:h,leave:function(){return"global"===e?Promise.resolve():(n.debug("stopping session "+e+"..."),a=!1,g({type:"leave",destination:e,domain:"global"}).then((function(){s=!1,u.execute("onLeft")})).catch((function(){s=!1,u.execute("onLeft")})))},onJoined:function(e){return s&&e(!1),u.add("onJoined",e)},onLeft:function(e){return s||e(),u.add("onLeft",e)},send:g,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:function(i,o){t.on(i,(function(t){if(t.domain===e)try{o(t)}catch(e){n.error("Callback failed: ".concat(e," \n ").concat(e.stack," \n msg was: ").concat(JSON.stringify(t)),e)}}))},loggedIn:function(e){return t.loggedIn(e)},connected:function(e){return t.connected(e)},disconnected:function(e){return t.disconnected(e)},get peerId(){return t.peerId},get domain(){return e}}}var vo=function(){function e(e,t,n){var i=this;this.connection=e,this.settings=t,this.logger=n,this.protocolVersion=3,this.datePrefix="#T42_DATE#",this.datePrefixLen=this.datePrefix.length,this.dateMinLen=this.datePrefixLen+1,this.datePrefixFirstChar=this.datePrefix[0],this.registry=ji(),this._isLoggedIn=!1,this.shouldTryLogin=!0,this.initialLogin=!0,this.initialLoginAttempts=3,this.sessions=[],e.disconnected((function(){i.handleDisconnected()})),this.ping()}return Object.defineProperty(e.prototype,"isLoggedIn",{get:function(){return this._isLoggedIn},enumerable:!1,configurable:!0}),e.prototype.processStringMessage=function(e){var t=this,n=JSON.parse(e,(function(e,n){if("string"!=typeof n)return n;if(n.length<t.dateMinLen)return n;if(n[0]!==t.datePrefixFirstChar)return n;if(n.substring(0,t.datePrefixLen)!==t.datePrefix)return n;try{var i=parseInt(n.substring(t.datePrefixLen,n.length),10);return isNaN(i)?n:new Date(i)}catch(e){return n}}));return{msg:n,msgType:n.type}},e.prototype.createStringMessage=function(e){var t=Date.prototype.toJSON;try{var n=this.datePrefix;return Date.prototype.toJSON=function(){return n+this.getTime()},JSON.stringify(e)}finally{Date.prototype.toJSON=t}},e.prototype.processObjectMessage=function(e){if(!e.type)throw new Error("Object should have type property");return{msg:e,msgType:e.type}},e.prototype.createObjectMessage=function(e){return e},e.prototype.login=function(e,t){return oi(this,void 0,void 0,(function(){var n,i,o,r,s,a,c,u,d,h;return ri(this,(function(l){switch(l.label){case 0:if(this.logger.debug("logging in..."),this.loginConfig=e,this.loginConfig||(this.loginConfig={username:"",password:""}),this.shouldTryLogin=!0,n={},this.connection.gatewayToken=e.gatewayToken,!e.gatewayToken)return[3,5];if(!t)return[3,4];l.label=1;case 1:return l.trys.push([1,3,,4]),[4,this.getNewGWToken()];case 2:return u=l.sent(),e.gatewayToken=u,[3,4];case 3:return i=l.sent(),this.logger.warn("failed to get GW token when reconnecting ".concat((null==i?void 0:i.message)||i)),[3,4];case 4:return n.method="gateway-token",n.token=e.gatewayToken,this.connection.gatewayToken=e.gatewayToken,[3,10];case 5:return"sspi"!==e.flowName?[3,9]:(n.provider="win",n.method="access-token",e.flowCallback&&e.sessionId?(o=n,[4,e.flowCallback(e.sessionId,null)]):[3,7]);case 6:return o.token=l.sent().data.toString("base64"),[3,8];case 7:throw new Error("Invalid SSPI config");case 8:return[3,10];case 9: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}l.label=10;case 10:r={type:"hello",identity:this.settings.identity,authentication:n},e.sessionId&&(r.request_id=e.sessionId),this.globalDomain=mo("global",this.connection,this.logger.subLogger("global-domain"),["welcome","token","authentication-request"]),s={skipPeerId:!0},this.initialLogin&&(s.retryInterval=this.settings.reconnectInterval,s.maxRetries=this.settings.reconnectAttempts),l.label=11;case 11:l.trys.push([11,19,20,21]),a=void 0,l.label=12;case 12:return[4,this.globalDomain.send(r,void 0,s)];case 13:return"authentication-request"!==(c=l.sent()).type?[3,16]:(u=Buffer.from(c.authentication.token,"base64"),e.flowCallback&&e.sessionId?(d=r.authentication,[4,e.flowCallback(e.sessionId,u)]):[3,15]);case 14:d.token=l.sent().data.toString("base64"),l.label=15;case 15:return r.request_id=e.sessionId,[3,12];case 16:if("welcome"===c.type)return a=c,[3,18];throw"error"===c.type?new Error("Authentication failed: "+c.reason):new Error("Unexpected message type during authentication: "+c.type);case 17:return[3,12];case 18:return this.initialLogin=!1,this.logger.debug("login successful with peerId "+a.peer_id),this.connection.peerId=a.peer_id,this.connection.resolvedIdentity=a.resolved_identity,this.connection.availableDomains=a.available_domains,a.options&&(this.connection.token=a.options.access_token,this.connection.info=a.options.info),this.setLoggedIn(!0),[2,a.resolved_identity];case 19:throw h=l.sent(),this.logger.error("error sending hello message - "+(h.message||h.msg||h.reason||h),h),h;case 20:return e&&e.flowCallback&&e.sessionId&&e.flowCallback(e.sessionId,null),[7];case 21:return[2]}}))}))},e.prototype.logout=function(){return oi(this,void 0,void 0,(function(){var e;return ri(this,(function(t){switch(t.label){case 0:return this.logger.debug("logging out..."),this.shouldTryLogin=!1,this.pingTimer&&clearTimeout(this.pingTimer),e=this.sessions.map((function(e){e.leave()})),[4,Promise.all(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.loggedIn=function(e){return this._isLoggedIn&&e(),this.registry.add("onLoggedIn",e)},e.prototype.domain=function(e,t,n,i){var o=this.sessions.filter((function(t){return t.domain===e}))[0];return o||(o=mo(e,this.connection,t,n,i),this.sessions.push(o)),o},e.prototype.handleDisconnected=function(){var e=this;if(this.setLoggedIn(!1),this.shouldTryLogin&&this.initialLogin){if(this.initialLoginAttempts<=0)return;this.initialLoginAttempts--}if(this.logger.debug("disconnected - will try new login?"+this.shouldTryLogin),this.shouldTryLogin){if(!this.loginConfig)throw new Error("no login info");this.connection.login(this.loginConfig,!0).catch((function(){setTimeout(e.handleDisconnected.bind(e),e.settings.reconnectInterval||1e3)}))}},e.prototype.setLoggedIn=function(e){this._isLoggedIn=e,this._isLoggedIn&&this.registry.execute("onLoggedIn")},e.prototype.ping=function(){var e=this;this.shouldTryLogin&&(this._isLoggedIn&&this.connection.send({type:"ping"}),this.pingTimer=setTimeout((function(){e.ping()}),3e4))},e.prototype.authToken=function(){return this.globalDomain?this.globalDomain.send({type:"create-token"}).then((function(e){return e.token})):Promise.reject(new Error("no global domain session"))},e.prototype.getNewGWToken=function(){if(void 0!==typeof window){var e=window.glue42gd;if(e)return e.getGWToken()}return Promise.reject(new Error("not running in GD"))},e}(),yo=function(){function e(e){this.specsNames=[],this.messages={},this.subs={},this.subsRefCount={},this.specs={};for(var t=0,n=e;t<n.length;t++){var i=n[t];this.specs[i.name]=i,this.specsNames.push(i.name)}}return e.prototype.init=function(e){var t=this;this.connection=e;for(var n=0,i=this.specsNames;n<i.length;n++)for(var o=i[n],r=function(n){var i=s.subsRefCount[n];if(i||(i=0),i+=1,s.subsRefCount[n]=i,i>1)return"continue";var o=e.on(n,(function(e){return t.processMessage(n,e)}));s.subs[n]=o},s=this,a=0,c=this.specs[o].types;a<c.length;a++){r(c[a])}},e.prototype.processMessage=function(e,t){if(!this.isDone&&t)for(var n=0,i=this.specsNames;n<i.length;n++){var o=i[n];if(-1!==this.specs[o].types.indexOf(e)){var r=this.messages[o]||[];this.messages[o]=r,r.push(t)}}},e.prototype.drain=function(e,t){var n;t&&(this.messages[e]||[]).forEach(t),delete this.messages[e];for(var i=0,o=this.specs[e].types;i<o.length;i++){var r=o[i];this.subsRefCount[r]-=1,this.subsRefCount[r]<=0&&(null===(n=this.connection)||void 0===n||n.off(this.subs[r]),delete this.subs[r],delete this.subsRefCount[r])}delete this.specs[e],this.specs.length||(this.isDone=!0)},e}(),bo=function(e,t,n){return new Promise((function(i,o){var r=setTimeout((function(){var e=n||"Promise timeout hit: ".concat(t);o(e)}),t);new Promise(e).then((function(e){clearTimeout(r),i(e)})).catch((function(e){clearTimeout(r),o(e)}))}))},wo=function(){function e(e,t,n){this.settings=e,this.logger=t,this.identity=n,this.iAmConnected=!1,this.parentReady=!1,this.rejected=!1,this.children=[],this.extContentAvailable=!1,this.extContentConnecting=!1,this.extContentConnected=!1,this.parentInExtMode=!1,this.webNamespace="g42_core_web",this.parentPingTimeout=5e3,this.connectionRequestTimeout=7e3,this.defaultTargetString="*",this.registry=ji(),this.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:function(){}},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:this.handleClientUnload.bind(this)},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)}},this.extContentAvailable=!!window.glue42ext,this.setUpMessageListener(),this.setUpUnload(),this.setupPlatformUnloadListener(),this.parentType=window.name.includes("#wsp")?"workspace":void 0}return e.prototype.manualSetReadyState=function(){this.iAmConnected=!0,this.parentReady=!0},Object.defineProperty(e.prototype,"transportWindowId",{get:function(){return this.publicWindowId},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"communicationId",{get:function(){return this._communicationId},enumerable:!1,configurable:!0}),e.prototype.sendObject=function(e){return oi(this,void 0,void 0,(function(){return ri(this,(function(t){if(this.extContentConnected)return[2,window.postMessage({glue42ExtOut:e},this.defaultTargetString)];if(!this.port)throw new Error("Cannot send message, because the port was not opened yet");return this.port.postMessage(e),[2]}))}))},Object.defineProperty(e.prototype,"isObjectBasedTransport",{get:function(){return!0},enumerable:!1,configurable:!0}),e.prototype.onMessage=function(e){return this.registry.add("onMessage",e)},e.prototype.send=function(){return Promise.reject("not supported")},e.prototype.onConnectedChanged=function(e){return this.registry.add("onConnectedChanged",e)},e.prototype.open=function(){return oi(this,void 0,void 0,(function(){return ri(this,(function(e){switch(e.label){case 0:return this.logger.debug("opening a connection to the web platform gateway."),[4,this.connect()];case 1:return e.sent(),this.notifyStatusChanged(!0),[2]}}))}))},e.prototype.close=function(){var e,t,n={glue42core:{type:this.messages.gatewayDisconnect.name,data:{clientId:this.myClientId,ownWindowId:null===(e=this.identity)||void 0===e?void 0:e.windowId}}};return null===(t=this.port)||void 0===t||t.postMessage(n),this.parentReady=!1,this.notifyStatusChanged(!1,"manual reconnection"),Promise.resolve()},e.prototype.name=function(){return"web-platform"},e.prototype.reconnect=function(){return oi(this,void 0,void 0,(function(){return ri(this,(function(e){switch(e.label){case 0:return[4,this.close()];case 1:return e.sent(),[2,Promise.resolve()]}}))}))},e.prototype.initiateInternalConnection=function(){var e=this;return new Promise((function(t,n){e.logger.debug("opening an internal web platform connection"),e.port=e.settings.port,e.iAmConnected?e.logger.warn("cannot open a new connection, because this client is currently connected"):(e.port.onmessage=function(i){var o,r;if(!e.iAmConnected||(null===(o=i.data)||void 0===o?void 0:o.glue42core)){var s=null===(r=i.data)||void 0===r?void 0:r.glue42core;s&&(s.type===e.messages.gatewayInternalConnect.name&&s.success&&(e.publicWindowId=e.settings.windowId,e.identity&&e.publicWindowId&&(e.identity.windowId=e.publicWindowId,e.identity.instance=e.publicWindowId),t()),s.type===e.messages.gatewayInternalConnect.name&&s.error&&n(s.error))}else e.registry.execute("onMessage",i.data)},e.port.postMessage({glue42core:{type:e.messages.gatewayInternalConnect.name}}))}))},e.prototype.initiateRemoteConnection=function(e){var t=this;return bo((function(n,i){var o;t.connectionResolve=n,t.connectionReject=i,t.myClientId=null!==(o=t.myClientId)&&void 0!==o?o:go();var r=t.getMyWindowId()||go(),s={glue42core:{type:t.messages.connectionRequest.name,clientId:t.myClientId,clientType:"child",bridgeInstanceId:r,selfAssignedWindowId:t.selfAssignedWindowId}};if(t.logger.debug("sending connection request"),t.extContentConnecting)return s.glue42core.clientType="child",s.glue42core.bridgeInstanceId=t.myClientId,s.glue42core.parentWindowId=t.parentWindowId,window.postMessage(s,t.defaultTargetString);if(!e)throw new Error("Cannot send a connection request, because no glue target was specified!");e.postMessage(s,t.defaultTargetString)}),this.connectionRequestTimeout,"The connection to the target glue window timed out")},e.prototype.isParentCheckSuccess=function(e){return oi(this,void 0,void 0,(function(){return ri(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,e];case 1:return t.sent(),[2,{success:!0}];case 2:return t.sent(),[2,{success:!1}];case 3:return[2]}}))}))},e.prototype.setUpMessageListener=function(){var e=this;this.settings.port?this.logger.debug("skipping generic message listener, because this is an internal client"):window.addEventListener("message",(function(t){var n,i=null===(n=t.data)||void 0===n?void 0:n.glue42core;if(i&&!e.rejected)if(e.checkMessageTypeValid(i.type)){var o=i.type;e.logger.debug("received valid glue42core message of type: ".concat(o)),e.messages[o].handle(t)}else e.logger.error("cannot handle the incoming glue42 core message, because the type is invalid: ".concat(i.type))}))},e.prototype.setUpUnload=function(){var e=this;this.settings.port?this.logger.debug("skipping unload event listener, because this is an internal client"):window.addEventListener("beforeunload",(function(){var t,n;if(!e.extContentConnected){var i={glue42core:{type:e.messages.clientUnload.name,data:{clientId:e.myClientId,ownWindowId:null===(t=e.identity)||void 0===t?void 0:t.windowId}}};e.parent&&e.parent.postMessage(i,e.defaultTargetString),null===(n=e.port)||void 0===n||n.postMessage(i)}}))},e.prototype.handlePlatformReady=function(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"},e.prototype.handleConnectionAccepted=function(e){var t,n=null===(t=e.data)||void 0===t?void 0:t.glue42core;return this.myClientId===n.clientId?this.handleAcceptanceOfMyRequest(n):this.handleAcceptanceOfGrandChildRequest(n,e)},e.prototype.handleAcceptanceOfMyRequest=function(e){var t=this;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.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||go()),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=function(e){return t.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")},e.prototype.processExtContentConnection=function(e){var t=this;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",(function(e){var n,i=null===(n=e.data)||void 0===n?void 0:n.glue42ExtInc;i&&t.registry.execute("onMessage",i)})),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve},e.prototype.handleAcceptanceOfGrandChildRequest=function(e,t){if(this.extContentConnecting||this.extContentConnected)this.logger.debug("cannot process acceptance of a grandchild, because I am connected to a content script");else{this.logger.debug("handling a connection accepted signal targeted at a grandchild: ".concat(e.clientId));var n=this.children.find((function(t){return t.grandChildId===e.clientId}));n?(n.connected=!0,this.logger.debug("the grandchild connection for ".concat(e.clientId," is set up, forwarding the success message and the gateway port")),e.parentWindowId=this.publicWindowId,n.source.postMessage(t.data,n.origin,[e.port])):this.logger.error("cannot handle connection accepted for grandchild: ".concat(e.clientId,", because there is no grandchild with this id"))}},e.prototype.handleConnectionRejected=function(){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&&(this.connectionReject("The platform connection was rejected. Most likely because this window was not created by a glue API call"),delete this.connectionReject)},e.prototype.handleConnectionRequest=function(e){if(this.extContentConnecting)this.logger.debug("This connection request event is targeted at the extension content");else{var t=e.source,n=e.data.glue42core;if(!n.clientType||"grandChild"!==n.clientType)return this.rejectConnectionRequest(t,e.origin,"rejecting a connection request, because the source was not opened by a glue API call");if(!n.clientId)return this.rejectConnectionRequest(t,e.origin,"rejecting a connection request, because the source did not provide a valid id");if(!this.parent)return this.rejectConnectionRequest(t,e.origin,"Cannot forward the connection request, because no direct connection to the platform was found");this.logger.debug("handling a connection request for a grandchild: ".concat(n.clientId)),this.children.push({grandChildId:n.clientId,source:t,connected:!1,origin:e.origin}),this.logger.debug("grandchild: ".concat(n.clientId," is prepared, forwarding connection request to the platform")),this.parent.postMessage(e.data,this.defaultTargetString)}},e.prototype.handleParentPing=function(e){if(this.parentReady)if(this.iAmConnected){var t={glue42core:{type:this.messages.parentReady.name}};this.extContentConnected&&(t.glue42core.extMode={windowId:this.myClientId});var n=e.source;this.logger.debug("responding to a parent ping with a ready message"),n.postMessage(t,e.origin)}else this.logger.debug("i am not fully connected yet, I am ignoring the parent ping");else this.logger.debug("my parent is not ready, I am ignoring the parent ping")},e.prototype.setupPlatformUnloadListener=function(){var e=this;this.onMessage((function(t){"platformUnload"===t.type&&(e.logger.debug("detected a web platform unload"),e.parentReady=!1,e.notifyStatusChanged(!1,"Gateway unloaded"))}))},e.prototype.handleManualUnload=function(){var e,t,n={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:null===(e=this.identity)||void 0===e?void 0:e.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:n},this.defaultTargetString);null===(t=this.port)||void 0===t||t.postMessage(n)},e.prototype.handleClientUnload=function(e){var t=e.data.glue42core,n=null==t?void 0:t.data.clientId;n?this.children.find((function(e){return e.grandChildId===n}))?(this.logger.debug("handling grandchild unload for id: ".concat(n)),this.children=this.children.filter((function(e){return e.grandChildId!==n}))):this.logger.warn("cannot process grand child unload, because this client is unaware of this grandchild"):this.logger.warn("cannot process grand child unload, because the provided id was not valid")},e.prototype.handlePlatformPing=function(){},e.prototype.notifyStatusChanged=function(e,t){this.iAmConnected=e,this.registry.execute("onConnectedChanged",e,t)},e.prototype.checkMessageTypeValid=function(e){return"string"==typeof e&&!!this.messages[e]},e.prototype.rejectConnectionRequest=function(e,t,n){this.rejected=!0,this.logger.error(n);var i={glue42core:{type:this.messages.connectionRejected.name}};e.postMessage(i,t)},e.prototype.requestConnectionPermissionFromExt=function(){var e=this;return this.waitForContentScript().then((function(){return bo((function(t,n){e.extConnectionResolve=t,e.extConnectionReject=n;e.logger.debug("permission request to the extension content script was sent"),window.postMessage({glue42core:{type:"extSetupRequest"}},e.defaultTargetString)}),e.parentPingTimeout,"Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out")}))},e.prototype.handleExtConnectionResponse=function(e){var t;if(!(null===(t=e.data)||void 0===t?void 0:t.glue42core).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.")},e.prototype.handleExtSetupRequest=function(){},e.prototype.handleGatewayDisconnect=function(){},e.prototype.handleGatewayInternalConnect=function(){},e.prototype.waitForContentScript=function(){var e;return!!(null===(e=window.glue42ext)||void 0===e?void 0:e.content)?Promise.resolve():bo((function(e){window.addEventListener("Glue42EXTReady",(function(){e()}))}),this.connectionRequestTimeout,"The content script was available, but was never heard to be ready")},e.prototype.connect=function(){return oi(this,void 0,void 0,(function(){return ri(this,(function(e){switch(e.label){case 0:return this.settings.port?[4,this.initiateInternalConnection()]:[3,2];case 1:return e.sent(),this.logger.debug("internal web platform connection completed"),[2];case 2:return this.logger.debug("opening a client web platform connection"),[4,this.findParent()];case 3:return e.sent(),[4,this.initiateRemoteConnection(this.parent)];case 4:return e.sent(),this.logger.debug("the client is connected"),[2]}}))}))},e.prototype.findParent=function(){var e;return oi(this,void 0,void 0,(function(){var t,n,i,o;return ri(this,(function(r){switch(r.label){case 0:if(t="Cannot initiate glue, because this window was not opened or created by a glue client",n=this.getPossibleParentsInWindow(window),i=this.getPossibleParentsOutsideWindow(null===(e=window.top)||void 0===e?void 0:e.opener,window.top),!(o=new Set(si(si([],n,!0),i,!0))).size&&!this.extContentAvailable)throw new Error(t);return o.size||!this.extContentAvailable?[3,2]:[4,this.requestConnectionPermissionFromExt()];case 1:case 4:return r.sent(),[2];case 2:return[4,this.isParentCheckSuccess(this.confirmParent(Array.from(o)))];case 3:if(r.sent().success)return this.logger.debug("The default parent was found!"),[2];if(!this.extContentAvailable)throw new Error(t);return[4,this.requestConnectionPermissionFromExt()]}}))}))},e.prototype.getPossibleParentsInWindow=function(e){return e&&e!==e.top?si([e.parent],this.getPossibleParentsInWindow(e.parent),!0):[]},e.prototype.getPossibleParentsOutsideWindow=function(e,t){return e&&t&&e!==t?si(si([e],this.getPossibleParentsInWindow(e),!0),this.getPossibleParentsOutsideWindow(e.opener,e),!0):[]},e.prototype.confirmParent=function(e){var t=this,n=bo((function(n){t.parentPingResolve=n;var i={glue42core:{type:t.messages.platformPing.name}};t.parentPingInterval=setInterval((function(){e.forEach((function(e){e.postMessage(i,t.defaultTargetString)}))}),1e3)}),this.parentPingTimeout,"Cannot initiate glue, because this window was not opened or created by a glue client");return n.catch((function(){t.parentPingInterval&&(clearInterval(t.parentPingInterval),delete t.parentPingInterval)})),n},e.prototype.getMyWindowId=function(){var e;return"workspace"===this.parentType?window.name.substring(0,window.name.indexOf("#wsp")):window===window.top?(null===(e=window.name)||void 0===e?void 0:e.includes("g42"))?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||"g42-".concat(go()),this.selfAssignedWindowId):void 0},e}(),Io=function(){function e(e){void 0===e&&(e=0),this.minSequenceInterval=e,this.queue=[],this.isExecutingQueue=!1}return e.prototype.enqueue=function(e){var t=this;return new Promise((function(n,i){t.queue.push({action:e,resolve:n,reject:i}),t.executeQueue()}))},e.prototype.executeQueue=function(){return oi(this,void 0,void 0,(function(){var e,t,n;return ri(this,(function(i){switch(i.label){case 0:if(this.isExecutingQueue)return[2];this.isExecutingQueue=!0,i.label=1;case 1:if(!this.queue.length)return[3,7];if(!(e=this.queue.shift()))return this.isExecutingQueue=!1,[2];i.label=2;case 2:return i.trys.push([2,4,,5]),[4,e.action()];case 3:return t=i.sent(),e.resolve(t),[3,5];case 4:return n=i.sent(),e.reject(n),[3,5];case 5:return[4,this.intervalBreak()];case 6:return i.sent(),[3,1];case 7:return this.isExecutingQueue=!1,[2]}}))}))},e.prototype.intervalBreak=function(){var e=this;return new Promise((function(t){return setTimeout(t,e.minSequenceInterval)}))},e}(),Co=function(){function e(e,t){if(this.settings=e,this.logger=t,this.messageHandlers={},this.ids=1,this.registry=ji(),this._connected=!1,this.isTrace=!1,this._swapTransport=!1,this._switchInProgress=!1,this._transportSubscriptions=[],this._sequelizer=new Io,(e=e||{}).reconnectAttempts=e.reconnectAttempts||10,e.reconnectInterval=e.reconnectInterval||1e3,e.inproc)this.transport=new Ai(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new Ei(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new wo(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new qi(e,t.subLogger("ws"))}this.isTrace=t.canPublish("trace"),t.debug("starting with ".concat(this.transport.name()," transport")),this.protocol=new vo(this,e,t.subLogger("protocol"));var 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}return Object.defineProperty(e.prototype,"protocolVersion",{get:function(){var e;return null===(e=this.protocol)||void 0===e?void 0:e.protocolVersion},enumerable:!1,configurable:!0}),e.prototype.switchTransport=function(e){return oi(this,void 0,void 0,(function(){var t=this;return ri(this,(function(n){return[2,this._sequelizer.enqueue((function(){return oi(t,void 0,void 0,(function(){var t,n,i;return ri(this,(function(o){switch(o.label){case 0: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");return this.logger.trace("Starting transport switch with settings: ".concat(JSON.stringify(e))),t="secondary"===e.type?this.getNewSecondaryTransport(e):this._defaultTransport,this._targetTransport=t,this._targetAuth="secondary"===e.type?this.getNewSecondaryAuth(e):this._defaultAuth,n=this.verifyConnection(),this._swapTransport=!0,this._switchInProgress=!0,this.logger.trace("The new transport has been set, closing the current transport"),[4,this.transport.close()];case 1:o.sent(),o.label=2;case 2:return o.trys.push([2,4,,5]),[4,n];case 3:return o.sent(),i=this.transport===t,this.logger.info("The reconnection after the switch was completed. Was the switch a success: ".concat(i)),this._switchInProgress=!1,[2,{success:i}];case 4:return o.sent(),this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."),this.switchTransport({type:"default"}),this._switchInProgress=!1,[2,{success:!1}];case 5:return[2]}}))}))}))]}))}))},e.prototype.onLibReAnnounced=function(e){return this.registry.add("libReAnnounced",e)},e.prototype.setLibReAnnounced=function(e){this.registry.execute("libReAnnounced",e)},e.prototype.send=function(e,t){if(this.transport.sendObject&&this.transport.isObjectBasedTransport){var n=this.protocol.createObjectMessage(e);return this.isTrace&&this.logger.trace(">> ".concat(JSON.stringify(n))),this.transport.sendObject(n,t)}var i=this.protocol.createStringMessage(e);return this.isTrace&&this.logger.trace(">> ".concat(i)),this.transport.send(i,t)},e.prototype.on=function(e,t){e=e.toLowerCase(),void 0===this.messageHandlers[e]&&(this.messageHandlers[e]={});var n=this.ids++;return this.messageHandlers[e][n]=t,{type:e,id:n}},e.prototype.off=function(e){delete this.messageHandlers[e.type.toLowerCase()][e.id]},Object.defineProperty(e.prototype,"isConnected",{get:function(){return this.protocol.isLoggedIn},enumerable:!1,configurable:!0}),e.prototype.connected=function(e){var t=this;return this.protocol.loggedIn((function(){var n=t.transport.name();e(n)}))},e.prototype.disconnected=function(e){return this.registry.add("disconnected",e)},e.prototype.login=function(e,t){return oi(this,void 0,void 0,(function(){var n,i,o;return ri(this,(function(r){switch(r.label){case 0:this._defaultAuth||(this._defaultAuth=e),this._swapTransport&&(this.logger.trace("Detected a transport swap, swapping transports"),n=this.transportSwap(),e=null!=n?n:e),this.logger.trace("Starting login for transport: ".concat(this.transport.name()," and auth ").concat(JSON.stringify(e))),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.transport.open()];case 2:return r.sent(),this.logger.trace("Transport: ".concat(this.transport.name()," opened, logging in")),Wi("connection").mark("transport-opened"),[4,this.protocol.login(e,t)];case 3:return i=r.sent(),this.logger.trace("Logged in with identity: ".concat(JSON.stringify(i))),Wi("connection").mark("protocol-logged-in"),[2,i];case 4:throw o=r.sent(),this._switchInProgress&&(this.logger.trace("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),new Error(o);case 5:return[2]}}))}))},e.prototype.logout=function(){return oi(this,void 0,void 0,(function(){return ri(this,(function(e){switch(e.label){case 0:return[4,this.protocol.logout()];case 1:return e.sent(),[4,this.transport.close()];case 2:return e.sent(),[2]}}))}))},e.prototype.loggedIn=function(e){return this.protocol.loggedIn(e)},e.prototype.domain=function(e,t,n){return this.protocol.domain(e,this.logger.subLogger("domain=".concat(e)),t,n)},e.prototype.authToken=function(){return this.protocol.authToken()},e.prototype.reconnect=function(){return this.transport.reconnect()},e.prototype.distributeMessage=function(e,t){var n=this,i=this.messageHandlers[t.toLowerCase()];void 0!==i&&Object.keys(i).forEach((function(t){var o=i[t];if(void 0!==o)try{o(e)}catch(e){try{n.logger.error("Message handler failed with ".concat(e.stack),e)}catch(t){console.log("Message handler failed",e)}}}))},e.prototype.handleConnectionChanged=function(e){this._connected!==e&&(this._connected=e,e?(this.settings.replaySpecs&&this.settings.replaySpecs.length&&(this.replayer=new yo(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):this.registry.execute("disconnected"))},e.prototype.handleTransportMessage=function(e){var t;t="string"==typeof e?this.protocol.processStringMessage(e):this.protocol.processObjectMessage(e),this.isTrace&&this.logger.trace("<< ".concat(JSON.stringify(t))),this.distributeMessage(t.msg,t.msgType)},e.prototype.verifyConnection=function(){var e=this;return bo((function(t){var n,i,o,r=(i=function(){n&&n(),t()},o=2,function(){0==--o&&i()});n=e.onLibReAnnounced((function(e){return"interop"===e.name||"contexts"===e.name?r():void 0}))}),1e4,"Transport switch timed out waiting for all libraries to be re-announced")},e.prototype.getNewSecondaryTransport=function(e){var t;if(!(null===(t=e.transportConfig)||void 0===t?void 0:t.url))throw new Error("Missing secondary transport URL.");return new qi(Object.assign({},this.settings,{ws:e.transportConfig.url,reconnectAttempts:1}),this.logger.subLogger("ws-secondary"))},e.prototype.getNewSecondaryAuth=function(e){var t;if(!(null===(t=e.transportConfig)||void 0===t?void 0:t.auth))throw new Error("Missing secondary transport auth information.");return e.transportConfig.auth},e.prototype.transportSwap=function(){if(this._swapTransport=!1,this._targetTransport&&this._targetAuth){this._transportSubscriptions.forEach((function(e){return e()})),this._transportSubscriptions=[],this.transport=this._targetTransport;var 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}this.logger.warn("Error while switching transports - either the target transport or auth is not defined: transport defined -> ".concat(!!this._defaultTransport,", auth defined -> ").concat(!!this._targetAuth,". Staying on the current one."))},e.prototype.prepareDefaultSwap=function(){var e=this;this._transportSubscriptions.forEach((function(e){return e()})),this._transportSubscriptions=[],this.transport.close().catch((function(t){return e.logger.warn("Error closing the ".concat(e.transport.name()," transport after a failed connection attempt: ").concat(JSON.stringify(t)))})),this._targetTransport=this._defaultTransport,this._targetAuth=this._defaultAuth,this._swapTransport=!0},e}(),So=["trace","debug","info","warn","error","off"],xo=function(){function e(e,t,n){this.name=e,this.parent=t,this.subLoggers=[],this.logFn=console,this.customLogFn=!1,this.name=e,this.path=t?"".concat(t.path,".").concat(e):e,this.loggerFullName="[".concat(this.path,"]"),this.includeTimeAndLevel=!n,n&&(this.logFn=n,this.customLogFn=!0)}return e.prototype.subLogger=function(t){var n=this.subLoggers.filter((function(e){return e.name===t}))[0];if(void 0!==n)return n;Object.keys(this).forEach((function(e){if(e===t)throw new Error("This sub logger name is not allowed.")}));var i=new e(t,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(i),i},e.prototype.publishLevel=function(e){var t;return e&&(this._publishLevel=e),this._publishLevel||(null===(t=this.parent)||void 0===t?void 0:t.publishLevel())},e.prototype.consoleLevel=function(e){var t;return e&&(this._consoleLevel=e),this._consoleLevel||(null===(t=this.parent)||void 0===t?void 0:t.consoleLevel())},e.prototype.log=function(e,t,n){this.publishMessage(t||"info",e,n)},e.prototype.trace=function(e){this.log(e,"trace")},e.prototype.debug=function(e){this.log(e,"debug")},e.prototype.info=function(e){this.log(e,"info")},e.prototype.warn=function(e){this.log(e,"warn")},e.prototype.error=function(e,t){this.log(e,"error")},e.prototype.canPublish=function(e,t){return So.indexOf(e)>=So.indexOf(t||this.consoleLevel()||"trace")},e.prototype.publishMessage=function(t,n,i){var o=this.loggerFullName;if("error"===t&&!i){var r=new Error;r.stack&&(n=n+"\n"+r.stack.split("\n").slice(3).join("\n"))}if(this.canPublish(t,this.publishLevel())){var s=e.Interop;if(s)try{s.methods({name:e.InteropMethodName}).length>0&&s.invoke(e.InteropMethodName,{msg:"".concat(n),logger:o,level:t})}catch(e){}}if(this.canPublish(t)){var a="";if(this.includeTimeAndLevel){var c=new Date,u="".concat(c.getHours(),":").concat(c.getMinutes(),":").concat(c.getSeconds(),":").concat(c.getMilliseconds());a="[".concat(u,"] [").concat(t,"] ")}var d="".concat(a).concat(o,": ").concat(n);switch(t){case"trace":this.logFn.debug(d);break;case"debug":this.logFn.debug?this.logFn.debug(d):this.logFn.log(d);break;case"info":this.logFn.info(d);break;case"warn":this.logFn.warn(d);break;case"error":this.logFn.error(d,i)}}},e.InteropMethodName="T42.AppLogger.Log",e}(),_o="create-context",Po="created",To="destroyed",ko="context-created",Mo="context-added",Ro="subscribe-context",jo="subscribed-context",Ao="unsubscribe-context",Eo="destroy-context",Oo="context-destroyed",No="update-context",Do="context-updated",Wo="joined",Lo={get name(){return"context"},get types(){return[_o,Po,To,ko,Mo,Ro,jo,Ao,Eo,Oo,No,Do,Wo]}},qo="6.0.3";var Fo=function(){function e(e,t,n,i){this.updateCallbacks={},this.contextId=e,this.name=t,this.isAnnounced=n,this.activityId=i,this.context={}}return e.prototype.hasCallbacks=function(){return Object.keys(this.updateCallbacks).length>0},e.prototype.getState=function(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0},e}(),Go={};!function(e,t){var n=200,i="__lodash_hash_undefined__",o=9007199254740991,r="[object Arguments]",s="[object Boolean]",a="[object Date]",c="[object Function]",u="[object GeneratorFunction]",d="[object Map]",h="[object Number]",l="[object Object]",p="[object Promise]",f="[object RegExp]",g="[object Set]",m="[object String]",v="[object Symbol]",y="[object WeakMap]",b="[object ArrayBuffer]",w="[object DataView]",I="[object Float32Array]",C="[object Float64Array]",S="[object Int8Array]",x="[object Int16Array]",_="[object Int32Array]",P="[object Uint8Array]",T="[object Uint8ClampedArray]",k="[object Uint16Array]",M="[object Uint32Array]",R=/\w*$/,j=/^\[object .+?Constructor\]$/,A=/^(?:0|[1-9]\d*)$/,E={};E[r]=E["[object Array]"]=E[b]=E[w]=E[s]=E[a]=E[I]=E[C]=E[S]=E[x]=E[_]=E[d]=E[h]=E[l]=E[f]=E[g]=E[m]=E[v]=E[P]=E[T]=E[k]=E[M]=!0,E["[object Error]"]=E[c]=E[y]=!1;var O="object"==typeof ki&&ki&&ki.Object===Object&&ki,N="object"==typeof self&&self&&self.Object===Object&&self,D=O||N||Function("return this")(),W=t&&!t.nodeType&&t,L=W&&e&&!e.nodeType&&e,q=L&&L.exports===W;function F(e,t){return e.set(t[0],t[1]),e}function G(e,t){return e.add(t),e}function U(e,t,n,i){var o=-1,r=e?e.length:0;for(i&&r&&(n=e[++o]);++o<r;)n=t(n,e[o],o,e);return n}function B(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function $(e){var t=-1,n=Array(e.size);return e.forEach((function(e,i){n[++t]=[i,e]})),n}function J(e,t){return function(n){return e(t(n))}}function H(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n}var K,V=Array.prototype,z=Function.prototype,Q=Object.prototype,X=D["__core-js_shared__"],Y=(K=/[^.]+$/.exec(X&&X.keys&&X.keys.IE_PROTO||""))?"Symbol(src)_1."+K:"",Z=z.toString,ee=Q.hasOwnProperty,te=Q.toString,ne=RegExp("^"+Z.call(ee).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ie=q?D.Buffer:void 0,oe=D.Symbol,re=D.Uint8Array,se=J(Object.getPrototypeOf,Object),ae=Object.create,ce=Q.propertyIsEnumerable,ue=V.splice,de=Object.getOwnPropertySymbols,he=ie?ie.isBuffer:void 0,le=J(Object.keys,Object),pe=Le(D,"DataView"),fe=Le(D,"Map"),ge=Le(D,"Promise"),me=Le(D,"Set"),ve=Le(D,"WeakMap"),ye=Le(Object,"create"),be=Be(pe),we=Be(fe),Ie=Be(ge),Ce=Be(me),Se=Be(ve),xe=oe?oe.prototype:void 0,_e=xe?xe.valueOf:void 0;function Pe(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 Me(e){this.__data__=new Te(e)}function Re(e,t){var n=Je(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&He(e)}(e)&&ee.call(e,"callee")&&(!ce.call(e,"callee")||te.call(e)==r)}(e)?function(e,t){for(var n=-1,i=Array(e);++n<e;)i[n]=t(n);return i}(e.length,String):[],i=n.length,o=!!i;for(var s in e)!t&&!ee.call(e,s)||o&&("length"==s||Ge(s,i))||n.push(s);return n}function je(e,t,n){var i=e[t];ee.call(e,t)&&$e(i,n)&&(void 0!==n||t in e)||(e[t]=n)}function Ae(e,t){for(var n=e.length;n--;)if($e(e[n][0],t))return n;return-1}function Ee(e,t,n,i,o,p,y){var j;if(i&&(j=p?i(e,o,p,y):i(e)),void 0!==j)return j;if(!ze(e))return e;var A=Je(e);if(A){if(j=function(e){var t=e.length,n=e.constructor(t);t&&"string"==typeof e[0]&&ee.call(e,"index")&&(n.index=e.index,n.input=e.input);return n}(e),!t)return function(e,t){var n=-1,i=e.length;t||(t=Array(i));for(;++n<i;)t[n]=e[n];return t}(e,j)}else{var O=Fe(e),N=O==c||O==u;if(Ke(e))return function(e,t){if(t)return e.slice();var n=new e.constructor(e.length);return e.copy(n),n}(e,t);if(O==l||O==r||N&&!p){if(B(e))return p?e:{};if(j=function(e){return"function"!=typeof e.constructor||Ue(e)?{}:(t=se(e),ze(t)?ae(t):{});var t}(N?{}:e),!t)return function(e,t){return De(e,qe(e),t)}(e,function(e,t){return e&&De(t,Qe(t),e)}(j,e))}else{if(!E[O])return p?e:{};j=function(e,t,n,i){var o=e.constructor;switch(t){case b:return Ne(e);case s:case a:return new o(+e);case w:return function(e,t){var n=t?Ne(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}(e,i);case I:case C:case S:case x:case _:case P:case T:case k:case M:return function(e,t){var n=t?Ne(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($(e),!0):$(e);return U(i,F,new e.constructor)}(e,i,n);case h:case m:return new o(e);case f:return function(e){var t=new e.constructor(e.source,R.exec(e));return t.lastIndex=e.lastIndex,t}(e);case g:return function(e,t,n){var i=t?n(H(e),!0):H(e);return U(i,G,new e.constructor)}(e,i,n);case v:return r=e,_e?Object(_e.call(r)):{}}var r}(e,O,Ee,t)}}y||(y=new Me);var D=y.get(e);if(D)return D;if(y.set(e,j),!A)var W=n?function(e){return function(e,t,n){var i=t(e);return Je(e)?i:function(e,t){for(var n=-1,i=t.length,o=e.length;++n<i;)e[o+n]=t[n];return e}(i,n(e))}(e,Qe,qe)}(e):Qe(e);return function(e,t){for(var n=-1,i=e?e.length:0;++n<i&&!1!==t(e[n],n,e););}(W||e,(function(o,r){W&&(o=e[r=o]),je(j,r,Ee(o,t,n,i,r,e,y))})),j}function Oe(e){return!(!ze(e)||(t=e,Y&&Y in t))&&(Ve(e)||B(e)?ne:j).test(Be(e));var t}function Ne(e){var t=new e.constructor(e.byteLength);return new re(t).set(new re(e)),t}function De(e,t,n,i){n||(n={});for(var o=-1,r=t.length;++o<r;){var s=t[o],a=i?i(n[s],e[s],s,n,e):void 0;je(n,s,void 0===a?e[s]:a)}return n}function We(e,t){var n,i,o=e.__data__;return("string"==(i=typeof(n=t))||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==n:null===n)?o["string"==typeof t?"string":"hash"]:o.map}function Le(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Oe(n)?n:void 0}Pe.prototype.clear=function(){this.__data__=ye?ye(null):{}},Pe.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},Pe.prototype.get=function(e){var t=this.__data__;if(ye){var n=t[e];return n===i?void 0:n}return ee.call(t,e)?t[e]:void 0},Pe.prototype.has=function(e){var t=this.__data__;return ye?void 0!==t[e]:ee.call(t,e)},Pe.prototype.set=function(e,t){return this.__data__[e]=ye&&void 0===t?i: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():ue.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 Pe,map:new(fe||Te),string:new Pe}},ke.prototype.delete=function(e){return We(this,e).delete(e)},ke.prototype.get=function(e){return We(this,e).get(e)},ke.prototype.has=function(e){return We(this,e).has(e)},ke.prototype.set=function(e,t){return We(this,e).set(e,t),this},Me.prototype.clear=function(){this.__data__=new Te},Me.prototype.delete=function(e){return this.__data__.delete(e)},Me.prototype.get=function(e){return this.__data__.get(e)},Me.prototype.has=function(e){return this.__data__.has(e)},Me.prototype.set=function(e,t){var i=this.__data__;if(i instanceof Te){var o=i.__data__;if(!fe||o.length<n-1)return o.push([e,t]),this;i=this.__data__=new ke(o)}return i.set(e,t),this};var qe=de?J(de,Object):function(){return[]},Fe=function(e){return te.call(e)};function Ge(e,t){return!!(t=null==t?o:t)&&("number"==typeof e||A.test(e))&&e>-1&&e%1==0&&e<t}function Ue(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Q)}function Be(e){if(null!=e){try{return Z.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function $e(e,t){return e===t||e!=e&&t!=t}(pe&&Fe(new pe(new ArrayBuffer(1)))!=w||fe&&Fe(new fe)!=d||ge&&Fe(ge.resolve())!=p||me&&Fe(new me)!=g||ve&&Fe(new ve)!=y)&&(Fe=function(e){var t=te.call(e),n=t==l?e.constructor:void 0,i=n?Be(n):void 0;if(i)switch(i){case be:return w;case we:return d;case Ie:return p;case Ce:return g;case Se:return y}return t});var Je=Array.isArray;function He(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=o}(e.length)&&!Ve(e)}var Ke=he||function(){return!1};function Ve(e){var t=ze(e)?te.call(e):"";return t==c||t==u}function ze(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Qe(e){return He(e)?Re(e):function(e){if(!Ue(e))return le(e);var t=[];for(var n in Object(e))ee.call(e,n)&&"constructor"!=n&&t.push(n);return t}(e)}e.exports=function(e){return Ee(e,!0,!0)}}({get exports(){return Go},set exports(e){Go=e}},Go);var Uo=Go;function Bo(e,t,n){try{if((null==n?void 0:n.canPublish("trace"))&&(null==n||n.trace("applying context delta ".concat(JSON.stringify(t)," on context ").concat(JSON.stringify(e)))),!t)return e;if(t.reset)return e=ii({},t.reset);if(e=$o(e,void 0),t.commands){for(var i=0,o=t.commands;i<o.length;i++){var r=o[i];"remove"===r.type?zo(e,r.path):"set"===r.type&&Ko(e,r.value,r.path)}return e}var s=t.added,a=t.updated,c=t.removed;return s&&Object.keys(s).forEach((function(t){e[t]=s[t]})),a&&Object.keys(a).forEach((function(t){Jo(t,e,a)})),c&&c.forEach((function(t){delete e[t]})),e}catch(i){return null==n||n.error("error applying context delta ".concat(JSON.stringify(t)," on context ").concat(JSON.stringify(e)),i),e}}function $o(e,t){return Uo(e)}var Jo=function(e,t,n){var i=n[e];if(void 0===i)return t;var o=t[e];return o&&i?"string"==typeof o||"number"==typeof o||"boolean"==typeof o||"string"==typeof i||"number"==typeof i||"boolean"==typeof i||Array.isArray(o)||Array.isArray(i)?(t[e]=i,t):(t[e]=Object.assign({},o,i),t):(t[e]=i,t)};function Ho(e,t){if(e===t)return!0;if(!(e instanceof Object&&t instanceof Object))return!1;if(e.constructor!==t.constructor)return!1;for(var 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(!Ho(e[n],t[n]))return!1}}for(var n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}function Ko(e,t,n){var i,o=n.split(".");for(i=0;i<o.length-1;i++)e[o[i]]||(e[o[i]]={}),"object"!=typeof e[o[i]]&&(e[o[i]]={}),e=e[o[i]];e[o[i]]=t}function Vo(e,t){return Object.keys(t).every((function(n){return"object"==typeof t[n]?Vo((null==e?void 0:e[n])||{},t[n]||{}):t[n]===(null==e?void 0:e[n])}))}function zo(e,t){var n,i=t.split(".");for(n=0;n<i.length-1;n++){if(!e[i[n]])return;e=e[i[n]]}delete e[i[n]]}var Qo,Xo=function(){function e(e){var t,n=this;this._contextNameToData={},this._gw3Subscriptions=[],this._nextCallbackSubscriptionNumber=0,this._creationPromises={},this._contextNameToId={},this._contextIdToName={},this._protocolVersion=void 0,this._contextsTempCache={},this._contextsSubscriptionsCache=[],this._connection=e.connection,this._logger=e.logger,this._trackAllContexts=e.trackAllContexts,this._reAnnounceKnownContexts=e.reAnnounceKnownContexts,this._gw3Session=this._connection.domain("global",[ko,jo,Oo,Do]),this._gw3Session.disconnected(this.resetState.bind(this)),this._gw3Session.onJoined((function(e){if(e)return n._reAnnounceKnownContexts?void n.reInitiateState().then((function(){return n._connection.setLibReAnnounced({name:"contexts"})})):n._connection.setLibReAnnounced({name:"contexts"})})),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),null===(t=this._connection.replayer)||void 0===t||t.drain(Lo.name,(function(e){var t=e.type;t&&(t===ko||t===Mo||t===Po?n.handleContextCreatedMessage(e):t===jo||t===Do||t===Wo?n.handleContextUpdatedMessage(e):t!==Oo&&t!==To||n.handleContextDestroyedMessage(e))}))}return Object.defineProperty(e.prototype,"protocolVersion",{get:function(){var e;if(!this._protocolVersion){var t=this._connection.availableDomains.find((function(e){return"context"===e.uri}));this._protocolVersion=null!==(e=null==t?void 0:t.version)&&void 0!==e?e:1}return this._protocolVersion},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"setPathSupported",{get:function(){return this.protocolVersion>=2},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){for(var e=0,t=this._gw3Subscriptions;e<t.length;e++){var n=t[e];this._connection.off(n)}for(var i in this._gw3Subscriptions.length=0,this._contextNameToData)this._contextNameToId.hasOwnProperty(i)&&delete this._contextNameToData[i]},e.prototype.createContext=function(e,t){var n=this;return e in this._creationPromises||(this._creationPromises[e]=this._gw3Session.send({type:_o,domain:"global",name:e,data:t,lifetime:"retained"}).then((function(i){n._contextNameToId[e]=i.context_id,n._contextIdToName[i.context_id]=e;var o=n._contextNameToData[e]||new Fo(i.context_id,e,!0,void 0);return o.isAnnounced=!0,o.name=e,o.contextId=i.context_id,o.context=i.data||$o(t),o.hasReceivedSnapshot=!0,n._contextNameToData[e]=o,delete n._creationPromises[e],i.context_id}))),this._creationPromises[e]},e.prototype.all=function(){var e=this;return Object.keys(this._contextNameToData).filter((function(t){return e._contextNameToData[t].isAnnounced}))},e.prototype.update=function(e,t){var n;return oi(this,void 0,void 0,(function(){var i,o,r,s=this;return ri(this,(function(a){switch(a.label){case 0:return t&&(t=$o(t)),e in this._creationPromises?[4,this._creationPromises[e]]:[3,2];case 1:a.sent(),a.label=2;case 2:return(i=this._contextNameToData[e])&&i.isAnnounced?(o=i.context,i.hasCallbacks()?[3,4]:[4,this.get(i.name)]):[2,this.createContext(e,t)];case 3:o=a.sent(),a.label=4;case 4:return r=2===this.protocolVersion?this.calculateContextDeltaV2(o,t):this.calculateContextDeltaV1(o,t),Object.keys(r.added).length||Object.keys(r.updated).length||r.removed.length||(null===(n=r.commands)||void 0===n?void 0:n.length)?[2,this._gw3Session.send({type:No,domain:"global",context_id:i.contextId,delta:r},{},{skipPeerId:!1}).then((function(e){s.handleUpdated(i,r,{updaterId:e.peer_id})}))]:[2,Promise.resolve()]}}))}))},e.prototype.set=function(e,t){return oi(this,void 0,void 0,(function(){var n,i=this;return ri(this,(function(o){switch(o.label){case 0:return t&&(t=$o(t)),e in this._creationPromises?[4,this._creationPromises[e]]:[3,2];case 1:o.sent(),o.label=2;case 2:return(n=this._contextNameToData[e])&&n.isAnnounced?[2,this._gw3Session.send({type:No,domain:"global",context_id:n.contextId,delta:{reset:t}},{},{skipPeerId:!1}).then((function(e){i.handleUpdated(n,{reset:t,added:{},removed:[],updated:{}},{updaterId:e.peer_id})}))]:[2,this.createContext(e,t)]}}))}))},e.prototype.setPath=function(e,t,n){return this.setPathSupported?this.setPaths(e,[{path:t,value:n}]):Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later")},e.prototype.setPaths=function(e,t){return oi(this,void 0,void 0,(function(){var n,i,o,r,s,a,c,u,d=this;return ri(this,(function(h){switch(h.label){case 0:return this.setPathSupported?(t&&(t=$o(t)),e in this._creationPromises?[4,this._creationPromises[e]]:[3,2]):[2,Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later")];case 1:h.sent(),h.label=2;case 2:if(!(n=this._contextNameToData[e])||!n.isAnnounced){for(i={},o=0,r=t;o<r.length;o++)u=r[o],Ko(i,u.value,u.path);return[2,this.createContext(e,i)]}for(s=[],a=0,c=t;a<c.length;a++)null===(u=c[a]).value?s.push({type:"remove",path:u.path}):s.push({type:"set",path:u.path,value:u.value});return[2,this._gw3Session.send({type:No,domain:"global",context_id:n.contextId,delta:{commands:s}},{},{skipPeerId:!1}).then((function(e){d.handleUpdated(n,{added:{},removed:[],updated:{},commands:s},{updaterId:e.peer_id})}))]}}))}))},e.prototype.get=function(e){var t;return oi(this,void 0,void 0,(function(){var n,i,o=this;return ri(this,(function(r){switch(r.label){case 0:return e in this._creationPromises?[4,this._creationPromises[e]]:[3,2];case 1:r.sent(),r.label=2;case 2:return(n=this._contextNameToData[e])&&n.isAnnounced?!n||n.hasCallbacks()&&n.hasReceivedSnapshot?(i=null!==(t=null==n?void 0:n.context)&&void 0!==t?t:{},[2,Promise.resolve($o(i))]):[2,new Promise((function(t){o.subscribe(e,(function(e,n,i,r){o.unsubscribe(r),t(e)}))}))]:[2,Promise.resolve({})]}}))}))},e.prototype.subscribe=function(e,t,n){return oi(this,void 0,void 0,(function(){var i,o,r,s,a=this;return ri(this,(function(c){switch(c.label){case 0:return e in this._creationPromises?[4,this._creationPromises[e]]:[3,2];case 1:c.sent(),c.label=2;case 2:return i=void 0===n?this._nextCallbackSubscriptionNumber:n,void 0===n&&(this._nextCallbackSubscriptionNumber+=1),this._contextsSubscriptionsCache.every((function(e){return e.subKey!==a._nextCallbackSubscriptionNumber}))&&this._contextsSubscriptionsCache.push({contextName:e,subKey:i,callback:t}),(o=this._contextNameToData[e])&&o.isAnnounced?(r=o.hasCallbacks(),o.updateCallbacks[i]=t,r||o.joinedActivity||o.context&&o.sentExplicitSubscription?(o.hasReceivedSnapshot&&(s=$o(o.context),t(s,s,[],i)),[2,Promise.resolve(i)]):[2,this.sendSubscribe(o).then((function(){return i}))]):(o=o||new Fo(void 0,e,!1,void 0),this._contextNameToData[e]=o,o.updateCallbacks[i]=t,[2,Promise.resolve(i)])}}))}))},e.prototype.unsubscribe=function(e){this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter((function(t){return t.subKey!==e}));for(var t=0,n=Object.keys(this._contextNameToData);t<n.length;t++){var i=n[t],o=this._contextNameToData[i];if(!o)return;var r=o.hasCallbacks();delete o.updateCallbacks[e],o.isAnnounced&&r&&!o.hasCallbacks()&&o.sentExplicitSubscription&&this.sendUnsubscribe(o),o.isAnnounced||o.hasCallbacks()||delete this._contextNameToData[i]}},e.prototype.destroy=function(e){return oi(this,void 0,void 0,(function(){var t;return ri(this,(function(n){switch(n.label){case 0:return e in this._creationPromises?[4,this._creationPromises[e]]:[3,2];case 1:n.sent(),n.label=2;case 2:return(t=this._contextNameToData[e])?[2,this._gw3Session.send({type:Eo,domain:"global",context_id:t.contextId}).then((function(e){}))]:[2,Promise.reject("context with ".concat(e," does not exist"))]}}))}))},e.prototype.handleUpdated=function(e,t,n){var i=e.context;e.context=Bo(e.context,t,this._logger),e.hasReceivedSnapshot=!0,this._contextNameToData[e.name]!==e||Ho(i,e.context)||this.invokeUpdateCallbacks(e,t,n)},e.prototype.subscribeToContextCreatedMessages=function(){for(var e=0,t=[Mo,ko,Po];e<t.length;e++){var n=t[e],i=this._connection.on(n,this.handleContextCreatedMessage.bind(this));this._gw3Subscriptions.push(i)}},e.prototype.handleContextCreatedMessage=function(e){var t=this,n=e.type;n===Po?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):n===Mo&&(this._contextNameToId[e.name]=e.context_id,this._contextIdToName[e.context_id]=e.name);var i=this._contextIdToName[e.context_id];if(!i)throw new Error("Received created event for context with unknown name: "+e.context_id);if(!this._contextNameToId[i])throw new Error("Received created event for context with unknown id: "+e.context_id);var o=this._contextNameToData[i];if(o){if(o.isAnnounced)return;if(!o.hasCallbacks())throw new Error("Assertion failure: contextData.hasCallbacks()");o.isAnnounced=!0,o.contextId=e.context_id,o.activityId=e.activity_id,o.sentExplicitSubscription||this.sendSubscribe(o)}else this._contextNameToData[i]=o=new Fo(e.context_id,i,!0,e.activity_id),this._trackAllContexts&&this.subscribe(i,(function(){})).then((function(e){return t._systemContextsSubKey=e}))},e.prototype.subscribeToContextUpdatedMessages=function(){for(var e=0,t=[Do,jo,Wo];e<t.length;e++){var n=t[e],i=this._connection.on(n,this.handleContextUpdatedMessage.bind(this));this._gw3Subscriptions.push(i)}},e.prototype.handleContextUpdatedMessage=function(e){var t=e.type,n=e.context_id,i=this._contextNameToData[this._contextIdToName[n]],o=!i||!i.isAnnounced;if(t===Wo)i||(i=this._contextNameToData[e.activity_id]||new Fo(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===jo?((i=i||new Fo(n,e.name,!0,void 0)).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: ".concat(n)));var r=i.context;if(i.hasReceivedSnapshot=!0,t===jo)i.context=e.data||{};else if(t===Wo)i.context=e.context_snapshot||{};else{if(t!==Do)throw new Error("Unrecognized context update message "+t);i.context=Bo(i.context,e.delta,this._logger)}!o&&Ho(i.context,r)&&t!==jo||this.invokeUpdateCallbacks(i,e.delta,{updaterId:e.updater_id})},e.prototype.invokeUpdateCallbacks=function(e,t,n){if((t=t||{added:{},updated:{},reset:{},removed:[]}).commands){t.added=t.updated=t.reset={},t.removed=[];for(var i=0,o=t.commands;i<o.length;i++){var r=o[i];"remove"===r.type?(-1===r.path.indexOf(".")&&t.removed.push(r.path),Ko(t.updated,null,r.path)):"set"===r.type&&Ko(t.updated,r.value,r.path)}}for(var s in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(s))try{(0,e.updateCallbacks[s])($o(e.context),$o(Object.assign({},t.added||{},t.updated||{},t.reset||{})),t.removed,parseInt(s,10),n)}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}},e.prototype.subscribeToContextDestroyedMessages=function(){for(var e=0,t=[Oo,To];e<t.length;e++){var n=t[e],i=this._connection.on(n,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(i)}},e.prototype.handleContextDestroyedMessage=function(e){var t,n;if(e.type===To){if(n=e.activity_id,!(t=this._contextNameToId[n]))return void this._logger.error("Received 'destroyed' for unknown activity: ".concat(e.activity_id))}else if(t=e.context_id,!(n=this._contextIdToName[t]))return void this._logger.error("Received 'destroyed' for unknown context: ".concat(e.context_id));delete this._contextIdToName[t],delete this._contextNameToId[n];var i=this._contextNameToData[n];delete this._contextNameToData[n],i&&i.isAnnounced||this._logger.error("Received 'destroyed' for unknown context: ".concat(t))},e.prototype.sendSubscribe=function(e){return e.sentExplicitSubscription=!0,this._gw3Session.send({type:Ro,domain:"global",context_id:e.contextId}).then((function(e){}))},e.prototype.sendUnsubscribe=function(e){return e.sentExplicitSubscription=!1,this._gw3Session.send({type:Ao,domain:"global",context_id:e.contextId}).then((function(e){}))},e.prototype.calculateContextDeltaV1=function(e,t){var n={added:{},updated:{},removed:[],reset:void 0};if(e)for(var i=0,o=Object.keys(e);i<o.length;i++){var r=o[i];-1===Object.keys(t).indexOf(r)||null===t[r]||Ho(e[r],t[r])||(n.updated[r]=t[r])}for(var s=0,a=Object.keys(t);s<a.length;s++){r=a[s];e&&-1!==Object.keys(e).indexOf(r)?null===t[r]&&n.removed.push(r):null!==t[r]&&(n.added[r]=t[r])}return n},e.prototype.calculateContextDeltaV2=function(e,t){for(var n,i,o={added:{},updated:{},removed:[],reset:void 0,commands:[]},r=0,s=Object.keys(t);r<s.length;r++){var a=s[r];if(null!==t[a])Ho(e?e[a]:null,t[a])||null===(n=o.commands)||void 0===n||n.push({type:"set",path:a,value:t[a]});else null===(i=o.commands)||void 0===i||i.push({type:"remove",path:a})}return o},e.prototype.resetState=function(){for(var e=this,t=0,n=this._gw3Subscriptions;t<n.length;t++){var i=n[t];this._connection.off(i)}this._systemContextsSubKey&&(this.unsubscribe(this._systemContextsSubKey),delete this._systemContextsSubKey),this._gw3Subscriptions=[],this._contextNameToId={},this._contextIdToName={},delete this._protocolVersion,this._contextsTempCache=Object.keys(this._contextNameToData).reduce((function(t,n){return t[n]=e._contextNameToData[n].context,t}),{}),this._contextNameToData={}},e.prototype.reInitiateState=function(){var e;return oi(this,void 0,void 0,(function(){var t,n,i,o,r,s,a=this;return ri(this,(function(c){switch(c.label){case 0:return this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),null===(e=this._connection.replayer)||void 0===e||e.drain(Lo.name,(function(e){var t=e.type;t&&(t===ko||t===Mo||t===Po?a.handleContextCreatedMessage(e):t===jo||t===Do||t===Wo?a.handleContextUpdatedMessage(e):t!==Oo&&t!==To||a.handleContextDestroyedMessage(e))})),[4,Promise.all(this._contextsSubscriptionsCache.map((function(e){return a.subscribe(e.contextName,e.callback,e.subKey)})))];case 1:return c.sent(),[4,this.flushQueue()];case 2:for(i in c.sent(),t=this._contextsTempCache,n=[],t)n.push(i);o=0,c.label=3;case 3:return o<n.length?(i=n[o])in t?(r=i,"object"!=typeof this._contextsTempCache[r]||0===Object.keys(this._contextsTempCache[r]).length?[3,6]:(s=this._contextsTempCache[r],this._logger.info("Re-announcing known context: ".concat(r)),[4,this.flushQueue()])):[3,6]:[3,7];case 4:return c.sent(),[4,this.update(r,s)];case 5:c.sent(),c.label=6;case 6:return o++,[3,3];case 7:return this._contextsTempCache={},this._logger.info("Contexts are re-announced"),[2]}}))}))},e.prototype.flushQueue=function(){return new Promise((function(e){return setTimeout((function(){return e()}),0)}))},e}(),Yo=function(){function e(e){this._bridge=new Xo(e)}return e.prototype.all=function(){return this._bridge.all()},e.prototype.update=function(e,t){return this.checkName(e),this.checkData(t),this._bridge.update(e,t)},e.prototype.set=function(e,t){return this.checkName(e),this.checkData(t),this._bridge.set(e,t)},e.prototype.setPath=function(e,t,n){return this.checkName(e),this.checkPath(t),""===t?(this.checkData(n),this.set(e,n)):this._bridge.setPath(e,t,n)},e.prototype.setPaths=function(e,t){if(this.checkName(e),!Array.isArray(t))throw new Error("Please provide the paths as an array of PathValues!");for(var n=0,i=t;n<i.length;n++){var o=i[n],r=o.path,s=o.value;this.checkPath(r),""===r&&this.checkData(s)}return this._bridge.setPaths(e,t)},e.prototype.subscribe=function(e,t){var n=this;if(this.checkName(e),"function"!=typeof t)throw new Error("Please provide the callback as a function!");return this._bridge.subscribe(e,(function(e,i,o,r,s){return t(e,i,o,(function(){return n._bridge.unsubscribe(r)}),s)})).then((function(e){return function(){n._bridge.unsubscribe(e)}}))},e.prototype.get=function(e){return this.checkName(e),this._bridge.get(e)},e.prototype.ready=function(){return Promise.resolve(this)},e.prototype.destroy=function(e){return this.checkName(e),this._bridge.destroy(e)},Object.defineProperty(e.prototype,"setPathSupported",{get:function(){return this._bridge.setPathSupported},enumerable:!1,configurable:!0}),e.prototype.checkName=function(e){if("string"!=typeof e||""===e)throw new Error("Please provide the name as a non-empty string!")},e.prototype.checkPath=function(e){if("string"!=typeof e)throw new Error("Please provide the path as a dot delimited string!")},e.prototype.checkData=function(e){if("object"!=typeof e)throw new Error("Please provide the data as an object!")},e}();function Zo(e,t,n){return"function"!=typeof t&&"function"!=typeof n?e:("function"!=typeof t?t=function(){}:"function"!=typeof n&&(n=function(){}),e.then(t,n))}function er(e,t,n){var i;void 0===e&&(e=0);var o=function(){i&&clearTimeout(i)};return t.then((function(){o()})).catch((function(){o()})),new Promise((function(t,o){i=setTimeout((function(){return o(n)}),e)}))}!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(Qo||(Qo={}));var tr=function(){function e(e,t,n,i){this.protocol=e,this.repo=t,this.instance=n,this.configuration=i}return e.prototype.subscribe=function(e,t,n,i,o){var r=this,s=function(e,n,i,s){var a;t.methodResponseTimeout=null!==(a=t.methodResponseTimeout)&&void 0!==a?a:t.waitTimeoutMs,r.protocol.client.subscribe(n,t,e,i,s,o)},a=new Promise((function(n,i){var o,a=function(e){n(e)},c=function(e){i(e)};if(e)if((o="string"==typeof e?{name:e}:e).name){void 0===t&&(t={});var u=t.target;if(void 0===u&&(u="best"),"string"!=typeof u||"all"===u||"best"===u){void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=t.method_response_timeout,void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=r.configuration.methodResponseTimeout)),void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=t.wait_for_method_timeout,void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=r.configuration.waitTimeoutMs));var d=0,h=r.getServerMethodsByFilterAndTarget(o,u);if(h.length>0)s(h,h[0].methods[0],a,c);else{var l=function(){if(u&&t.waitTimeoutMs)if(d+=500,(h=r.getServerMethodsByFilterAndTarget(o,u)).length>0){var n=h[0].methods[0];s(h,n,a,c)}else if(d>=t.waitTimeoutMs){s(h,"string"==typeof e?{name:e}:e,a,c)}else setTimeout(l,500)};setTimeout(l,500)}}else i(new Error('"'.concat(u,'" is not a valid target. Valid targets are "all", "best", or an instance.')))}else i("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");else i("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.")}));return Zo(a,n,i)},e.prototype.servers=function(e){var t=void 0===e?void 0:ii({},e);return this.getServers(t).map((function(e){return e.server.instance}))},e.prototype.methods=function(e){return e="string"==typeof e?{name:e}:ii({},e),this.getMethods(e)},e.prototype.methodsForInstance=function(e){return this.getMethodsForInstance(e)},e.prototype.methodAdded=function(e){return this.repo.onMethodAdded(e)},e.prototype.methodRemoved=function(e){return this.repo.onMethodRemoved(e)},e.prototype.serverAdded=function(e){return this.repo.onServerAdded(e)},e.prototype.serverRemoved=function(e){return this.repo.onServerRemoved((function(t,n){e(t,n)}))},e.prototype.serverMethodAdded=function(e){return this.repo.onServerMethodAdded((function(t,n){e({server:t,method:n})}))},e.prototype.serverMethodRemoved=function(e){return this.repo.onServerMethodRemoved((function(t,n){e({server:t,method:n})}))},e.prototype.invoke=function(e,t,n,i,o,r){return oi(this,void 0,void 0,(function(){var s,a=this;return ri(this,(function(c){return s=function(){return oi(a,void 0,void 0,(function(){var o,r,s,a,c,u,d,h,l,p,f,g,m=this;return ri(this,(function(v){switch(v.label){case 0:if(!(o="string"==typeof e?{name:e}:ii({},e)).name)return[2,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(t||(t={}),n||(n="best"),"string"==typeof n&&"all"!==n&&"best"!==n&&"skipMine"!==n)return[2,Promise.reject(new Error('"'.concat(n,'" is not a valid target. Valid targets are "all" and "best".')))];if(i||(i={}),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)),void 0!==i.waitTimeoutMs&&"number"!=typeof i.waitTimeoutMs)return[2,Promise.reject(new Error('"'.concat(i.waitTimeoutMs,'" is not a valid number for "waitTimeoutMs" ')))];if("object"!=typeof t)return[2,Promise.reject(new Error("The method arguments must be an object. method: ".concat(o.name)))];if(0!==(r=this.getServerMethodsByFilterAndTarget(o,n)).length)return[3,4];v.label=1;case 1:return v.trys.push([1,3,,4]),[4,this.tryToAwaitForMethods(o,n,i)];case 2:return r=v.sent(),[3,4];case 3:return v.sent(),s=ii(ii({},o),{getServers:function(){return[]},supportsStreaming:!1,objectTypes:null!==(p=o.objectTypes)&&void 0!==p?p:[],flags:null!==(g=null===(f=o.flags)||void 0===f?void 0:f.metadata)&&void 0!==g?g:{}}),a={method:s,called_with:t,message:"Can not find a method matching ".concat(JSON.stringify(e)," with server filter ").concat(JSON.stringify(n)),executed_by:void 0,returned:void 0,status:void 0},[2,Promise.reject(a)];case 4:return c=i.methodResponseTimeoutMs,u=i,d=r.map((function(e){var n=go(),i=e.methods[0],o=e.server,r=m.protocol.client.invoke(n,i,t,o,u);return Promise.race([r,er(c,r,{invocationId:n,message:"Invocation timeout (".concat(c," ms) reached for method name: ").concat(null==i?void 0:i.name,", target instance: ").concat(JSON.stringify(o.instance),", options: ").concat(JSON.stringify(u)),status:Qo.Error})])})),[4,Promise.all(d)];case 5:return h=v.sent(),l=this.getInvocationResultObj(h,o,t),h.every((function(e){return e.status===Qo.Error}))?[2,Promise.reject(l)]:[2,l]}}))}))},[2,Zo(s(),o,r)]}))}))},e.prototype.getInvocationResultObj=function(e,t,n){var i=e.filter((function(e){return e.status===Qo.Success})).reduce((function(e,i){return e=si(si([],e,!0),[{executed_by:i.instance,returned:i.result,called_with:n,method:t,message:i.message,status:i.status}],!1)}),[]),o=e.filter((function(e){return e.status===Qo.Error})).reduce((function(e,i){return e=si(si([],e,!0),[{executed_by:i.instance,called_with:n,name:t.name,message:i.message}],!1)}),[]),r=e[0];return{method:t,called_with:n,returned:r.result,executed_by:r.instance,all_return_values:i,all_errors:o,message:r.message,status:r.status}},e.prototype.tryToAwaitForMethods=function(e,t,n){var i=this;return new Promise((function(o,r){if(0!==n.waitTimeoutMs)var s=0,a=setInterval((function(){s+=500;var c=i.getServerMethodsByFilterAndTarget(e,t);if(c.length>0)clearInterval(a),o(c);else if(s>=(n.waitTimeoutMs||1e4))return clearInterval(a),void r()}),500);else r()}))},e.prototype.filterByTarget=function(e,t){var n=this;if("string"!=typeof e){return(Array.isArray(e)?e:[e]).reduce((function(e,i){var o=t.filter((function(e){return n.instanceMatch(i,e.server.instance)}));return e.concat(o)}),[])}if("all"===e)return si([],t,!0);if("best"===e){var i=t.find((function(e){return e.server.instance.isLocal}));if(i)return[i];if(void 0!==t[0])return[t[0]]}else if("skipMine"===e)return t.filter((function(e){return e.server.instance.peerId!==n.instance.peerId}));return[]},e.prototype.instanceMatch=function(e,t){return this.containsProps(e,t)},e.prototype.methodMatch=function(e,t){return this.containsProps(e,t)},e.prototype.containsProps=function(e,t){return Object.keys(e).filter((function(t){return 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((function(n){var i,o=e[n],r=t[n];switch(n){case"objectTypes":i=(o||[]).every((function(e){return(r||[]).includes(e)}));break;case"flags":i=Vo(r||{},o||{});break;default:i=String(o).toLowerCase()===String(r).toLowerCase()}return i}))},e.prototype.getMethods=function(e){var t=this;return void 0===e?this.repo.getMethods():this.repo.getMethods().filter((function(n){return t.methodMatch(e,n)}))},e.prototype.getMethodsForInstance=function(e){var t=this,n=this.repo.getServers().filter((function(n){return t.instanceMatch(e,n.instance)}));if(0===n.length)return[];var i={};return 1===n.length?i=n[0].methods:n.forEach((function(e){Object.keys(e.methods).forEach((function(t){var n=e.methods[t];i[n.identifier]=n}))})),Object.keys(i).map((function(e){return i[e]}))},e.prototype.getServers=function(e){var t=this,n=this.repo.getServers();return void 0===e?n.map((function(e){return{server:e,methods:[]}})):n.reduce((function(n,i){var o=Object.values(i.methods).filter((function(n){return t.methodMatch(e,n)}));return o.length>0&&n.push({server:i,methods:o}),n}),[])},e.prototype.getServerMethodsByFilterAndTarget=function(e,t){var n=this.getServers(e);return this.filterByTarget(t,n)},e}(),nr=function(){function e(e,t,n){this.protocol=e,this.repoMethod=t,this.subscription=n}return Object.defineProperty(e.prototype,"stream",{get:function(){if(!this.repoMethod.stream)throw new Error("no stream");return this.repoMethod.stream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"arguments",{get:function(){return this.subscription.arguments||{}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"branchKey",{get:function(){return this.subscription.branchKey},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"instance",{get:function(){if(!this.subscription.instance)throw new Error("no instance");return this.subscription.instance},enumerable:!1,configurable:!0}),e.prototype.close=function(){this.protocol.server.closeSingleSubscription(this.repoMethod,this.subscription)},e.prototype.push=function(e){this.protocol.server.pushDataToSingle(this.repoMethod,this.subscription,e)},e}(),ir=function(){function e(e,t,n){this.protocol=e,this.repoMethod=t,this.requestContext=n,this.arguments=n.arguments,this.instance=n.instance}return e.prototype.accept=function(){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,"")},e.prototype.acceptOnBranch=function(e){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,e)},e.prototype.reject=function(e){this.protocol.server.rejectRequest(this.requestContext,this.repoMethod,e)},e}(),or=function(){function e(e,t){var n=this;this.protocol=e,this.server=t,e.server.onSubRequest((function(e,t){return n.handleSubRequest(e,t)})),e.server.onSubAdded((function(e,t){return n.handleSubAdded(e,t)})),e.server.onSubRemoved((function(e,t){return n.handleSubRemoved(e,t)}))}return e.prototype.handleSubRequest=function(e,t){if(t&&t.streamCallbacks&&"function"==typeof t.streamCallbacks.subscriptionRequestHandler){var n=new ir(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(n)}},e.prototype.handleSubAdded=function(e,t){if(t&&t.streamCallbacks&&"function"==typeof t.streamCallbacks.subscriptionAddedHandler){var n=new nr(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(n)}},e.prototype.handleSubRemoved=function(e,t){if(t&&t.streamCallbacks&&"function"==typeof t.streamCallbacks.subscriptionRemovedHandler){var n=new nr(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(n)}},e}(),rr=function(){function e(e,t,n){this.key=e,this.protocol=t,this.repoMethod=n}return e.prototype.subscriptions=function(){var e=this;return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map((function(t){return new nr(e.protocol,e.repoMethod,t)}))},e.prototype.close=function(){this.protocol.server.closeAllSubscriptions(this.repoMethod,this.key)},e.prototype.push=function(e){this.protocol.server.pushData(this.repoMethod,e,[this.key])},e}(),sr=function(){function e(e,t,n){this._protocol=e,this._repoMethod=t,this._server=n,this.name=this._repoMethod.definition.name}return e.prototype.branches=function(e){var t=this,n=this._protocol.server.getBranchList(this._repoMethod);return e?n.indexOf(e)>-1?new rr(e,this._protocol,this._repoMethod):void 0:n.map((function(e){return new rr(e,t._protocol,t._repoMethod)}))},e.prototype.branch=function(e){return this.branches(e)},e.prototype.subscriptions=function(){var e=this;return this._protocol.server.getSubscriptionList(this._repoMethod).map((function(t){return new nr(e._protocol,e._repoMethod,t)}))},Object.defineProperty(e.prototype,"definition",{get:function(){var e,t=this._repoMethod.definition;return{accepts:t.accepts,description:t.description,displayName:t.displayName,name:t.name,objectTypes:t.objectTypes,returns:t.returns,supportsStreaming:t.supportsStreaming,flags:null===(e=t.flags)||void 0===e?void 0:e.metadata}},enumerable:!1,configurable:!0}),e.prototype.close=function(){this._protocol.server.closeAllSubscriptions(this._repoMethod),this._server.unregister(this._repoMethod.definition,!0)},e.prototype.push=function(e,t){if("string"!=typeof t&&!Array.isArray(t)&&void 0!==t)throw new Error("invalid branches should be string or string array");if("object"!=typeof e)throw new Error("Invalid arguments. Data must be an object.");this._protocol.server.pushData(this._repoMethod,e,t)},e.prototype.updateRepoMethod=function(e){this._repoMethod=e},e}(),ar=function(){function e(e,t){this.protocol=e,this.serverRepository=t,this.invocations=0,this.currentlyUnregistering={},this.streaming=new or(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}return e.prototype.createStream=function(e,t,n,i,o){var r=this,s=new Promise((function(n,i){if(e){var s;if(!(s="string"==typeof e?{name:""+e}:ii({},e)).name)return i("The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ".concat(JSON.stringify(s)));if(r.serverRepository.getList().some((function(e){return e.definition.name===s.name})))return i('A stream with the name "'.concat(s.name,'" already exists! Please, provide a unique name for the stream.'));s.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=function(e){e.accept()});var a=r.serverRepository.add({definition:s,streamCallbacks:t,protocolState:{}});r.protocol.server.createStream(a).then((function(){var e;o?(e=o,o.updateRepoMethod(a)):e=new sr(r.protocol,a,r),a.stream=e,n(e)})).catch((function(e){a.repoId&&r.serverRepository.remove(a.repoId),i(e)}))}else 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.")}));return Zo(s,n,i)},e.prototype.register=function(e,t){var n=this;if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject("The second parameter must be a callback function. Method: ".concat("string"==typeof e?e:e.name));var i=function(e,i){return oi(n,void 0,void 0,(function(){var n,o,r;return ri(this,(function(s){switch(s.label){case 0:return s.trys.push([0,4,,5]),(n=t(e.args,e.instance))&&"function"==typeof n.then?[4,n]:[3,2];case 1:return o=s.sent(),i(void 0,o),[3,3];case 2:i(void 0,n),s.label=3;case 3:return[3,5];case 4:return r=s.sent(),i(null!=r?r:"",null!=r?r:""),[3,5];case 5:return[2]}}))}))};return i.userCallback=t,this.registerCore(e,i)},e.prototype.registerAsync=function(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject("The second parameter must be a callback function. Method: ".concat("string"==typeof e?e:e.name));var n=function(e,n){try{var i=!1,o=function(e){i||n(void 0,e),i=!0},r=function(e){i||(e||(e=""),n(e,e)),i=!0},s=t(e.args,e.instance,o,r);s&&"function"==typeof s.then&&s.then(o).catch(r)}catch(e){n(e,void 0)}};return n.userCallbackAsync=t,this.registerCore(e,n)},e.prototype.unregister=function(e,t){return void 0===t&&(t=!1),oi(this,void 0,void 0,(function(){var n,i;return ri(this,(function(o){switch(o.label){case 0:return void 0===e?[2,Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.")]:"function"!=typeof e?[3,2]:[4,this.unregisterWithPredicate(e,t)];case 1:case 3:return o.sent(),[2];case 2:return void 0===(n="string"==typeof e?{name:e}:e).name?[2,Promise.reject("Method name is required. Cannot find a method if the method name is undefined!")]:(i=this.serverRepository.getList().find((function(e){return e.definition.name===n.name&&(e.definition.supportsStreaming||!1)===t})))?[4,this.removeMethodsOrStreams([i])]:[2,Promise.reject('Method with a name "'.concat(n.name,'" does not exist or is not registered by your application!'))]}}))}))},e.prototype.unregisterWithPredicate=function(e,t){return oi(this,void 0,void 0,(function(){var n;return ri(this,(function(i){switch(i.label){case 0:return(n=this.serverRepository.getList().filter((function(t){return e(t.definition)})).filter((function(e){return(e.definition.supportsStreaming||!1)===t})))&&0!==n.length?[4,this.removeMethodsOrStreams(n)]:[2,Promise.reject("Could not find a ".concat(t?"stream":"method"," matching the specified condition!"))];case 1:return i.sent(),[2]}}))}))},e.prototype.removeMethodsOrStreams=function(e){var t=this,n=[];return e.forEach((function(e){var i=t.protocol.server.unregister(e).then((function(){e.repoId&&t.serverRepository.remove(e.repoId)}));n.push(i),t.addAsCurrentlyUnregistering(e.definition.name,i)})),Promise.all(n)},e.prototype.addAsCurrentlyUnregistering=function(e,t){return oi(this,void 0,void 0,(function(){var n,i=this;return ri(this,(function(o){return n=new Promise((function(e){return setTimeout(e,5e3)})),this.currentlyUnregistering[e]=Promise.race([t,n]).then((function(){delete i.currentlyUnregistering[e]})),[2]}))}))},e.prototype.registerCore=function(e,t){return oi(this,void 0,void 0,(function(){var n,i,o,r=this;return ri(this,(function(s){switch(s.label){case 0:return(n="string"==typeof e?{name:""+e}:ii({},e)).name?(i=this.currentlyUnregistering[n.name])?[4,i]:[3,2]:[2,Promise.reject("Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ".concat(JSON.stringify(e)))];case 1:s.sent(),s.label=2;case 2:return this.serverRepository.getList().some((function(e){return e.definition.name===n.name}))?[2,Promise.reject('A method with the name "'.concat(n.name,'" already exists! Please, provide a unique name for the method.'))]:n.supportsStreaming?[2,Promise.reject("When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “".concat(n.name,"” to be a stream, please use the “glue.interop.createStream()” method."))]:(o=this.serverRepository.add({definition:n,theFunction:t,protocolState:{}}),[2,this.protocol.server.register(o).catch((function(e){throw(null==o?void 0:o.repoId)&&r.serverRepository.remove(o.repoId),e}))])}}))}))},e.prototype.onMethodInvoked=function(e,t,n){var i=this;e&&e.theFunction&&e.theFunction(n,(function(n,o){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: ".concat(Object.keys(n))}o?("object"!=typeof o||Array.isArray(o))&&(o={_value:o}):o={},i.protocol.server.methodInvocationResult(e,t,n,o)}))},e}(),cr=function(){function e(e,t,n){var i=this;this.wrapped={},this.wrapped.getMethods=function(){return e.methodsForInstance(this)},this.wrapped.getStreams=function(){return e.methodsForInstance(this).filter((function(e){return e.supportsStreaming}))},t&&this.refreshWrappedObject(t),n&&(n.loggedIn((function(){i.refresh(n)})),this.refresh(n))}return e.prototype.unwrap=function(){return this.wrapped},e.prototype.refresh=function(e){if(e){var t=null==e?void 0:e.resolvedIdentity,n=Object.assign({},null!=t?t:{},{peerId:null==e?void 0:e.peerId});this.refreshWrappedObject(n)}},e.prototype.refreshWrappedObject=function(e){var t,n,i,o,r=this;Object.keys(e).forEach((function(t){r.wrapped[t]=e[t]})),this.wrapped.user=e.user,this.wrapped.instance=e.instance,this.wrapped.application=null!==(t=e.application)&&void 0!==t?t:go(),this.wrapped.applicationName=e.applicationName,this.wrapped.pid=null!==(i=null!==(n=e.pid)&&void 0!==n?n:e.process)&&void 0!==i?i: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=null===(o=e.isLocal)||void 0===o||o,this.wrapped.api=e.api,this.wrapped.service=e.service,this.wrapped.peerId=e.peerId},e}(),ur=function(e){return ii(ii({},e),{flags:e.flags.metadata||{}})},dr=function(){function e(e,t){this.logger=e,this.API=t,this.servers={},this.methodsCount={},this.callbacks=ji();var n=this.API.instance.peerId;this.myServer={id:n,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[n]=this.myServer}return e.prototype.addServer=function(e,t){this.logger.debug("adding server ".concat(t));var n=this.servers[t];if(n)return n.id;var i=new cr(this.API,e),o={id:t,methods:{},instance:i.unwrap(),wrapper:i};return this.servers[t]=o,this.callbacks.execute("onServerAdded",o.instance),t},e.prototype.removeServerById=function(e,t){var n=this,i=this.servers[e];i?(this.logger.debug("removing server ".concat(e)),Object.keys(i.methods).forEach((function(t){n.removeServerMethod(e,t)})),delete this.servers[e],this.callbacks.execute("onServerRemoved",i.instance,t)):this.logger.warn("not aware of server ".concat(e,", my state ").concat(JSON.stringify(Object.keys(this.servers))))},e.prototype.addServerMethod=function(e,t){var n,i=this.servers[e];if(!i)throw new Error("server does not exists");if(!i.methods[t.id]){var o=this.createMethodIdentifier(t),r=this,s={identifier:o,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:null!==(n=t.flags)&&void 0!==n?n:{},getServers:function(){return r.getServersByMethod(o)}};s.object_types=s.objectTypes,s.display_name=s.displayName,s.version=s.version,i.methods[t.id]=s;var a=ur(s);return this.methodsCount[o]||(this.methodsCount[o]=0,this.callbacks.execute("onMethodAdded",a)),this.methodsCount[o]=this.methodsCount[o]+1,this.callbacks.execute("onServerMethodAdded",i.instance,a),s}},e.prototype.removeServerMethod=function(e,t){var n=this.servers[e];if(!n)throw new Error("server does not exists");var i=n.methods[t];delete n.methods[t];var o=ur(i);this.methodsCount[i.identifier]=this.methodsCount[i.identifier]-1,0===this.methodsCount[i.identifier]&&this.callbacks.execute("onMethodRemoved",o),this.callbacks.execute("onServerMethodRemoved",n.instance,o)},e.prototype.getMethods=function(){return this.extractMethodsFromServers(Object.values(this.servers)).map(ur)},e.prototype.getServers=function(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)},e.prototype.onServerAdded=function(e){var t=this.callbacks.add("onServerAdded",e),n=this.getServers().map((function(e){return e.instance}));return this.returnUnsubWithDelayedReplay(t,n,e)},e.prototype.onMethodAdded=function(e){var t=this.callbacks.add("onMethodAdded",e),n=this.getMethods();return this.returnUnsubWithDelayedReplay(t,n,e)},e.prototype.onServerMethodAdded=function(e){var t=this.callbacks.add("onServerMethodAdded",e),n=!1,i=this.getServers();return setTimeout((function(){i.forEach((function(t){var i=t.methods;Object.keys(i).forEach((function(o){n||e(t.instance,i[o])}))}))}),0),function(){n=!0,t()}},e.prototype.onMethodRemoved=function(e){return this.callbacks.add("onMethodRemoved",e)},e.prototype.onServerRemoved=function(e){return this.callbacks.add("onServerRemoved",e)},e.prototype.onServerMethodRemoved=function(e){return this.callbacks.add("onServerMethodRemoved",e)},e.prototype.getServerById=function(e){return this.hideServerMethodSystemFlags(this.servers[e])},e.prototype.reset=function(){var e,t=this;Object.keys(this.servers).forEach((function(e){t.removeServerById(e,"reset")})),this.servers=((e={})[this.myServer.id]=this.myServer,e),this.methodsCount={}},e.prototype.createMethodIdentifier=function(e){var t,n,i=null!==(t=e.input_signature)&&void 0!==t?t:"",o=null!==(n=e.result_signature)&&void 0!==n?n:"";return(e.name+i+o).toLowerCase()},e.prototype.getServersByMethod=function(e){var t=[];return Object.values(this.servers).forEach((function(n){Object.values(n.methods).forEach((function(i){i.identifier===e&&t.push(n.instance)}))})),t},e.prototype.returnUnsubWithDelayedReplay=function(e,t,n){var i=!1;return setTimeout((function(){t.forEach((function(e){i||n(e)}))}),0),function(){i=!0,e()}},e.prototype.hideServerMethodSystemFlags=function(e){var t={};return Object.entries(e.methods).forEach((function(e){var n=e[0],i=e[1];t[n]=ur(i)})),ii(ii({},e),{methods:t})},e.prototype.extractMethodsFromServers=function(e){return Object.values(e).reduce((function(e,t){return si(si([],e,!0),Object.values(t.methods),!0)}),[])},e}(),hr=function(){function e(){this.nextId=0,this.methods=[]}return e.prototype.add=function(e){return e.repoId=String(this.nextId),this.nextId+=1,this.methods.push(e),e},e.prototype.remove=function(e){if("string"!=typeof e)return new TypeError("Expecting a string");this.methods=this.methods.filter((function(t){return t.repoId!==e}))},e.prototype.getById=function(e){if("string"==typeof e)return this.methods.find((function(t){return t.repoId===e}))},e.prototype.getList=function(){return this.methods.map((function(e){return e}))},e.prototype.length=function(){return this.methods.length},e.prototype.reset=function(){this.methods=[]},e}(),lr="onSubscriptionRequest",pr="onSubscriptionAdded",fr="onSubscriptionRemoved",gr=function(){function e(e,t,n){var i=this;this.session=e,this.repository=t,this.serverRepository=n,this.ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure",this.callbacks=ji(),this.nextStreamId=0,e.on("add-interest",(function(e){i.handleAddInterest(e)})),e.on("remove-interest",(function(e){i.handleRemoveInterest(e)}))}return e.prototype.acceptRequestOnBranch=function(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.");var i=this.getStreamId(t,n),o=e.msg.subscription_id,r={id:o,arguments:e.arguments,instance:e.instance,branchKey:n,streamId:i,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[o]=r,this.session.sendFireAndForget({type:"accepted",subscription_id:o,stream_id:i}),this.callbacks.execute(pr,r,t)},e.prototype.rejectRequest=function(e,t,n){"string"!=typeof n&&(n=""),this.sendSubscriptionFailed("Subscription rejected by user. "+n,e.msg.subscription_id)},e.prototype.pushData=function(e,t,n){var i=this;if("object"==typeof e&&Array.isArray(e.protocolState.branchKeyToStreamIdMap)){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((function(e){return!n||0===n.length||n.indexOf(e.key)>=0})).map((function(e){return e.streamId})).forEach((function(e){var n={type:"publish",stream_id:e,data:t};i.session.sendFireAndForget(n)}))}},e.prototype.pushDataToSingle=function(e,t,n){if("object"!=typeof n)throw new Error("Invalid arguments. Data must be an object.");var i={type:"post",subscription_id:t.id,data:n};this.session.sendFireAndForget(i)},e.prototype.closeSingleSubscription=function(e,t){e.protocolState.subscriptionsMap&&delete e.protocolState.subscriptionsMap[t.id];var n={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(n),t.instance,this.callbacks.execute(fr,t,e)},e.prototype.closeMultipleSubscriptions=function(e,t){var n=this;if("object"==typeof e&&"object"==typeof e.protocolState.subscriptionsMap&&e.protocolState.subscriptionsMap){var i=e.protocolState.subscriptionsMap,o=Object.keys(i).map((function(e){return i[e]}));"string"==typeof t&&(o=o.filter((function(e){return e.branchKey===t}))),o.forEach((function(e){delete i[e.id];var t={type:"drop-subscription",subscription_id:e.id,reason:"Server dropping all subscriptions on stream_id: "+e.streamId};n.session.sendFireAndForget(t)}))}},e.prototype.getSubscriptionList=function(e,t){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];var n=e.protocolState.subscriptionsMap,i=Object.keys(n).map((function(e){return n[e]}));return"string"!=typeof t?i:i.filter((function(e){return e.branchKey===t}))},e.prototype.getBranchList=function(e){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];var t=e.protocolState.subscriptionsMap,n=Object.keys(t).map((function(e){return t[e]})),i=[];return n.forEach((function(e){var t="";"object"==typeof e&&"string"==typeof e.branchKey&&(t=e.branchKey),-1===i.indexOf(t)&&i.push(t)})),i},e.prototype.onSubAdded=function(e){this.onSubscriptionLifetimeEvent(pr,e)},e.prototype.onSubRequest=function(e){this.onSubscriptionLifetimeEvent(lr,e)},e.prototype.onSubRemoved=function(e){this.onSubscriptionLifetimeEvent(fr,e)},e.prototype.handleRemoveInterest=function(e){var t=this.serverRepository.getById(e.method_id);if("string"==typeof e.subscription_id&&"object"==typeof t&&t.protocolState.subscriptionsMap&&"object"==typeof t.protocolState.subscriptionsMap[e.subscription_id]){var n=t.protocolState.subscriptionsMap[e.subscription_id];delete t.protocolState.subscriptionsMap[e.subscription_id],this.callbacks.execute(fr,n,t)}},e.prototype.onSubscriptionLifetimeEvent=function(e,t){this.callbacks.add(e,t)},e.prototype.getNextStreamId=function(){return this.nextStreamId+++""},e.prototype.handleAddInterest=function(e){var t=this.repository.getServerById(e.caller_id).instance,n={msg:e,arguments:e.arguments_kv||{},instance:t},i=this.serverRepository.getById(e.method_id);if(void 0!==i)i.protocolState.subscriptionsMap&&i.protocolState.subscriptionsMap[e.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+e.subscription_id+" already exists.",e.subscription_id):this.callbacks.execute(lr,n,i);else{var o="No method with id "+e.method_id+" on this server.";this.sendSubscriptionFailed(o,e.subscription_id)}},e.prototype.sendSubscriptionFailed=function(e,t){var n={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:e,request_id:t};this.session.sendFireAndForget(n)},e.prototype.getStreamId=function(e,t){if("string"!=typeof t&&(t=""),!e.protocolState.branchKeyToStreamIdMap)throw new Error("streaming ".concat(e.definition.name," method without protocol state"));var n=e.protocolState.branchKeyToStreamIdMap.filter((function(e){return e.key===t}))[0],i=n?n.streamId:void 0;return"string"==typeof i&&""!==i||(i=this.getNextStreamId(),e.protocolState.branchKeyToStreamIdMap.push({key:t,streamId:i})),i},e}(),mr=function(){function e(e,t,n,i){var o=this;this.session=e,this.clientRepository=t,this.serverRepository=n,this.logger=i,this.callbacks=ji(),this.streaming=new gr(e,t,n),this.session.on("invoke",(function(e){return o.handleInvokeMessage(e)}))}return e.prototype.createStream=function(e){return e.protocolState.subscriptionsMap={},e.protocolState.branchKeyToStreamIdMap=[],this.register(e,!0)},e.prototype.register=function(e,t){var n,i=this,o=e.definition,r=Object.assign({},{metadata:null!==(n=o.flags)&&void 0!==n?n:{}},{streaming:t||!1}),s={type:"register",methods:[{id:e.repoId,name:o.name,display_name:o.displayName,description:o.description,version:o.version,flags:r,object_types:o.objectTypes||o.object_types,input_signature:o.accepts,result_signature:o.returns,restrictions:void 0}]};return this.session.send(s,{methodId:e.repoId}).then((function(){i.logger.debug("registered method "+e.definition.name+" with id "+e.repoId)})).catch((function(t){throw i.logger.warn("failed to register method ".concat(e.definition.name," with id ").concat(e.repoId," - ").concat(JSON.stringify(t))),t}))},e.prototype.onInvoked=function(e){this.callbacks.add("onInvoked",e)},e.prototype.methodInvocationResult=function(e,t,n,i){var o;o=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(o)},e.prototype.unregister=function(e){return oi(this,void 0,void 0,(function(){var t;return ri(this,(function(n){switch(n.label){case 0:return t={type:"unregister",methods:[e.repoId]},[4,this.session.send(t)];case 1:return n.sent(),[2]}}))}))},e.prototype.getBranchList=function(e){return this.streaming.getBranchList(e)},e.prototype.getSubscriptionList=function(e,t){return this.streaming.getSubscriptionList(e,t)},e.prototype.closeAllSubscriptions=function(e,t){this.streaming.closeMultipleSubscriptions(e,t)},e.prototype.pushData=function(e,t,n){this.streaming.pushData(e,t,n)},e.prototype.pushDataToSingle=function(e,t,n){this.streaming.pushDataToSingle(e,t,n)},e.prototype.closeSingleSubscription=function(e,t){this.streaming.closeSingleSubscription(e,t)},e.prototype.acceptRequestOnBranch=function(e,t,n){this.streaming.acceptRequestOnBranch(e,t,n)},e.prototype.rejectRequest=function(e,t,n){this.streaming.rejectRequest(e,t,n)},e.prototype.onSubRequest=function(e){this.streaming.onSubRequest(e)},e.prototype.onSubAdded=function(e){this.streaming.onSubAdded(e)},e.prototype.onSubRemoved=function(e){this.streaming.onSubRemoved(e)},e.prototype.handleInvokeMessage=function(e){var t=e.invocation_id,n=e.caller_id,i=e.method_id,o=e.arguments_kv,r=this.serverRepository.getList().filter((function(e){return e.repoId===i}))[0];if(void 0!==r){var s={args:o,instance:this.clientRepository.getServerById(n).instance};this.callbacks.execute("onInvoked",r,t,s)}},e}(),vr=function(){function e(e,t){this.repository=e,this.subscriptionData=t}return Object.defineProperty(e.prototype,"requestArguments",{get:function(){return this.subscriptionData.params.arguments||{}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"servers",{get:function(){var e=this;return this.subscriptionData.trackedServers.filter((function(e){return e.subscriptionId})).map((function(t){return e.repository.getServerById(t.serverId).instance}))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"serverInstance",{get:function(){return this.servers[0]},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stream",{get:function(){return this.subscriptionData.method},enumerable:!1,configurable:!0}),e.prototype.onData=function(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((function(t){e(t)}))},e.prototype.onClosed=function(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onClosed.push(e)},e.prototype.onFailed=function(e){},e.prototype.onConnected=function(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onConnected.push(e)},e.prototype.close=function(){this.subscriptionData.close()},e.prototype.setNewSubscription=function(e){this.subscriptionData=e},e}(),yr=function(){function e(e){this.config=e,this.cache=[],this.timeoutIds=[]}return e.prototype.add=function(e){var t=this,n=go();this.cache.push({id:n,element:e});var i=setTimeout((function(){var e=t.cache.findIndex((function(e){return e.id===n}));e<0||t.cache.splice(e,1)}),this.config.ELEMENT_TTL_MS);this.timeoutIds.push(i)},e.prototype.flush=function(){var e=this.cache.map((function(e){return e.element}));return this.timeoutIds.forEach((function(e){return clearInterval(e)})),this.cache=[],this.timeoutIds=[],e},e}(),br="awaitingAccept",wr="subscribed",Ir="Subscription failed.",Cr="Subscription rejected.",Sr="ClientInitiated",xr=function(){function e(e,t,n){var i=this;this.session=e,this.repository=t,this.logger=n,this.subscriptionsList={},this.timedCache=new yr({ELEMENT_TTL_MS:1e4}),this.subscriptionIdToLocalKeyMap={},this.nextSubLocalKey=0,this.handleErrorSubscribing=function(e){var t=e._tag,n=t.subLocalKey,o=i.subscriptionsList[n];if("object"==typeof o&&(o.trackedServers=o.trackedServers.filter((function(e){return e.serverId!==t.serverId})),o.trackedServers.length<=0)){if(clearTimeout(o.timeoutId),o.status===br){var r="string"==typeof e.reason&&""!==e.reason?' Publisher said "'+e.reason+'".':" No reason given.",s="object"==typeof o.params.arguments?JSON.stringify(o.params.arguments):"{}";o.error({message:Cr+r+" Called with:"+s,called_with:o.params.arguments,method:o.method})}else o.status===wr&&i.callOnClosedHandlers(o);delete i.subscriptionsList[n]}},this.handleSubscribed=function(e){var t=e._tag.subLocalKey,n=i.subscriptionsList[t];if("object"==typeof n){var o=e._tag.serverId,r=n.trackedServers.filter((function(e){return e.serverId===o}))[0];if("object"==typeof r){r.subscriptionId=e.subscription_id,i.subscriptionIdToLocalKeyMap[e.subscription_id]=t;var s=n.status===br;if(n.status=wr,s){var a=!1,c=n.subscription;c?(c.setNewSubscription(n),n.success(c),a=!0):(c=new vr(i.repository,n),n.subscription=c,n.success(c));for(var u=0,d=n.handlers.onConnected;u<d.length;u++){var h=d[u];try{h(c.serverInstance,a)}catch(e){}}}}}},this.handleEventData=function(e){var t=i.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0!==t){var n=i.subscriptionsList[t];if("object"==typeof n){var o=n.trackedServers.filter((function(t){return t.subscriptionId===e.subscription_id}));if(1===o.length){var r=e.oob,s=o[0].serverId,a=function(){return{data:e.data,server:i.repository.getServerById(s).instance,requestArguments:n.params.arguments,message:void 0,private:r}},c=n.handlers.onData,u=n.queued.data;c.length>0?c.forEach((function(e){"function"==typeof e&&e(a())})):u.push(a())}}}},this.handleSubscriptionCancelled=function(e){var t=i.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0!==t){var n=i.subscriptionsList[t];if("object"==typeof n){var o=n.trackedServers.length-1;n.trackedServers=n.trackedServers.filter((function(t){return t.subscriptionId!==e.subscription_id||(n.queued.closers.push(t.serverId),!1)})),n.trackedServers.length===o&&(n.trackedServers.length<=0&&(i.timedCache.add(n),clearTimeout(n.timeoutId),i.callOnClosedHandlers(n),delete i.subscriptionsList[t]),delete i.subscriptionIdToLocalKeyMap[e.subscription_id])}}},e.on("subscribed",this.handleSubscribed),e.on("event",this.handleEventData),e.on("subscription-cancelled",this.handleSubscriptionCancelled)}return e.prototype.subscribe=function(e,t,n,i,o,r){var s=this;if(0!==n.length){var a=this.getNextSubscriptionLocalKey(),c=this.registerSubscription(a,e,t,i,o,t.methodResponseTimeout||1e4,r);"object"==typeof c?n.forEach((function(n){var i=n.server.id,o=n.methods.find((function(t){return t.name===e.name}));if(o){c.trackedServers.push({serverId:i,subscriptionId:void 0});var r={type:"subscribe",server_id:i,method_id:o.gatewayId,arguments_kv:t.arguments};s.session.send(r,{serverId:i,subLocalKey:a}).then((function(e){return s.handleSubscribed(e)})).catch((function(e){return s.handleErrorSubscribing(e)}))}else s.logger.error("can not find method ".concat(e.name," for target ").concat(n.server.id))})):o({method:e,called_with:t.arguments,message:Ir+" Unable to register the user callbacks."})}else o({method:e,called_with:t.arguments,message:Ir+" No available servers matched the target params."})},e.prototype.drainSubscriptions=function(){var e=Object.values(this.subscriptionsList);return this.subscriptionsList={},this.subscriptionIdToLocalKeyMap={},e},e.prototype.drainSubscriptionsCache=function(){return this.timedCache.flush()},e.prototype.getNextSubscriptionLocalKey=function(){var e=this.nextSubLocalKey;return this.nextSubLocalKey+=1,e},e.prototype.registerSubscription=function(e,t,n,i,o,r,s){var a=this,c={localKey:e,status:br,method:t,params:n,success:i,error:o,trackedServers:[],handlers:{onData:(null==s?void 0:s.handlers.onData)||[],onClosed:(null==s?void 0:s.handlers.onClosed)||[],onConnected:(null==s?void 0:s.handlers.onConnected)||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:function(){return a.closeSubscription(e)},subscription:null==s?void 0:s.subscription};return s||(n.onData&&c.handlers.onData.push(n.onData),n.onClosed&&c.handlers.onClosed.push(n.onClosed),n.onConnected&&c.handlers.onConnected.push(n.onConnected)),this.subscriptionsList[e]=c,c.timeoutId=setTimeout((function(){if(void 0!==a.subscriptionsList[e]){var i=a.subscriptionsList[e];i.status===br?(o({method:t,called_with:n.arguments,message:Ir+" Subscription attempt timed out after "+r+" ms."}),delete a.subscriptionsList[e]):i.status===wr&&i.trackedServers.length>0&&(i.trackedServers=i.trackedServers.filter((function(e){return void 0!==e.subscriptionId})),delete i.timeoutId,i.trackedServers.length<=0&&(a.callOnClosedHandlers(i),delete a.subscriptionsList[e]))}}),r),c},e.prototype.callOnClosedHandlers=function(e,t){var n,i=e.queued.closers.length,o=i>0?e.queued.closers[i-1]:null;void 0!==o&&"string"==typeof o&&(n=this.repository.getServerById(o).instance),e.handlers.onClosed.forEach((function(i){"function"==typeof i&&i({message:t||"ServerInitiated",requestArguments:e.params.arguments||{},server:n,stream:e.method})}))},e.prototype.closeSubscription=function(e){var t=this,n=this.subscriptionsList[e];"object"==typeof n&&(n.trackedServers.forEach((function(e){void 0!==e.subscriptionId&&(n.queued.closers.push(e.serverId),t.session.sendFireAndForget({type:"unsubscribe",subscription_id:e.subscriptionId,reason_uri:"",reason:Sr}),delete t.subscriptionIdToLocalKeyMap[e.subscriptionId])})),n.trackedServers=[],this.callOnClosedHandlers(n,Sr),delete this.subscriptionsList[e])},e}(),_r=function(){function e(e,t,n){var i=this;this.session=e,this.repository=t,this.logger=n,e.on("peer-added",(function(e){return i.handlePeerAdded(e)})),e.on("peer-removed",(function(e){return i.handlePeerRemoved(e)})),e.on("methods-added",(function(e){return i.handleMethodsAddedMessage(e)})),e.on("methods-removed",(function(e){return i.handleMethodsRemovedMessage(e)})),this.streaming=new xr(e,t,n)}return e.prototype.subscribe=function(e,t,n,i,o,r){this.streaming.subscribe(e,t,n,i,o,r)},e.prototype.invoke=function(e,t,n,i){var o=this,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((function(e){return o.handleResultMessage(e)})).catch((function(e){return o.handleInvocationError(e)}))},e.prototype.drainSubscriptions=function(){return this.streaming.drainSubscriptions()},e.prototype.drainSubscriptionsCache=function(){return this.streaming.drainSubscriptionsCache()},e.prototype.handlePeerAdded=function(e){var t=e.new_peer_id,n=e.identity,i=!e.meta||e.meta.local,o=Number(n.process),r={machine:n.machine,pid:isNaN(o)?n.process:o,instance:n.instance,application:n.application,applicationName:n.applicationName,environment:n.environment,region:n.region,user:n.user,windowId:n.windowId,peerId:t,api:n.api,isLocal:i};this.repository.addServer(r,t)},e.prototype.handlePeerRemoved=function(e){var t=e.removed_id,n=e.reason;this.repository.removeServerById(t,n)},e.prototype.handleMethodsAddedMessage=function(e){var t=this,n=e.server_id;e.methods.forEach((function(e){t.repository.addServerMethod(n,e)}))},e.prototype.handleMethodsRemovedMessage=function(e){var t=this,n=e.server_id,i=e.methods,o=this.repository.getServerById(n);Object.keys(o.methods).forEach((function(e){var r=o.methods[e];i.indexOf(r.gatewayId)>-1&&t.repository.removeServerMethod(n,e)}))},e.prototype.handleResultMessage=function(e){var t=e._tag.invocationId,n=e.result,i=e._tag.serverId;return{invocationId:t,result:n,instance:this.repository.getServerById(i).instance,status:Qo.Success,message:""}},e.prototype.handleInvocationError=function(e){if(this.logger.debug("handle invocation error ".concat(JSON.stringify(e))),"_tag"in e){var t=e._tag.invocationId,n=e._tag.serverId,i=this.repository.getServerById(n),o=e.reason;return{invocationId:t,result:e.context,instance:i.instance,status:Qo.Error,message:o}}return{invocationId:"",message:e.message,status:Qo.Error,error:e}},e}();function Pr(e,t,n,i,o,r){var s,a=o.logger.subLogger("gw3-protocol"),c=new Promise((function(e){s=e})),u=t.domain("agm",["subscribed"]),d=new mr(u,n,i,a.subLogger("server")),h=new _r(u,n,a.subLogger("client"));return u.onJoined((function(o){n.addServer(e,t.peerId),o?function(){return oi(this,void 0,void 0,(function(){var e,t,n,o,s,c,u,d,l,p,f;return ri(this,(function(g){switch(g.label){case 0:for(a.info("reconnected - will replay registered methods and subscriptions"),h.drainSubscriptionsCache().forEach((function(e){var t=e.method,n=Object.assign({},e.params);a.info("trying to soft-re-subscribe to method ".concat(t.name,", with params: ").concat(JSON.stringify(n))),r.client.subscribe(t,n,void 0,void 0,e).then((function(){return a.info("soft-subscribing to method ".concat(t.name," DONE"))})).catch((function(e){return a.warn("subscribing to method ".concat(t.name," failed: ").concat(JSON.stringify(e),"}"))}))})),e=[],t=h.drainSubscriptions(),n=function(t){var n=t.method,i=Object.assign({},t.params);a.info("trying to re-subscribe to method ".concat(n.name,", with params: ").concat(JSON.stringify(i))),e.push(r.client.subscribe(n,i,void 0,void 0,t).then((function(){return a.info("subscribing to method ".concat(n.name," DONE"))})))},o=0,s=t;o<s.length;o++)c=s[o],n(c);for(u=i.getList(),i.reset(),d=function(t){var n=t.definition;a.info("re-publishing method ".concat(n.name)),t.stream?e.push(r.server.createStream(n,t.streamCallbacks,void 0,void 0,t.stream).then((function(){return a.info("subscribing to method ".concat(n.name," DONE"))}))):t.theFunction&&t.theFunction.userCallback?e.push(r.register(n,t.theFunction.userCallback).then((function(){return a.info("subscribing to method ".concat(n.name," DONE"))}))):t.theFunction&&t.theFunction.userCallbackAsync&&e.push(r.registerAsync(n,t.theFunction.userCallbackAsync).then((function(){return a.info("subscribing to method ".concat(n.name," DONE"))}))),a.info("re-publishing method ".concat(n.name," DONE"))},l=0,p=u;l<p.length;l++)f=p[l],d(f);return[4,Promise.all(e)];case 1:return g.sent(),a.info("Interop is re-announced"),[2]}}))}))}().then((function(){return t.setLibReAnnounced({name:"interop"})})).catch((function(e){return a.warn("Error while re-announcing interop: ".concat(JSON.stringify(e)))})):s&&(s({client:h,server:d}),s=void 0)})),u.onLeft((function(){n.reset()})),u.join(),c}var Tr=function(){function e(e){var t=this;if(void 0===e)throw new Error("configuration is required");if(void 0===e.connection)throw new Error("configuration.connections is required");var n,i=e.connection;if("number"!=typeof e.methodResponseTimeout&&(e.methodResponseTimeout=3e4),"number"!=typeof e.waitTimeoutMs&&(e.waitTimeoutMs=3e4),this.unwrappedInstance=new cr(this,void 0,i),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new dr(e.logger.subLogger("cRep"),this),this.serverRepository=new hr,3!==i.protocolVersion)throw new Error("protocol ".concat(i.protocolVersion," not supported"));n=Pr(this.instance,i,this.clientRepository,this.serverRepository,e,this),this.readyPromise=n.then((function(n){return t.protocol=n,t.client=new tr(t.protocol,t.clientRepository,t.instance,e),t.server=new ar(t.protocol,t.serverRepository),t}))}return e.prototype.ready=function(){return this.readyPromise},e.prototype.serverRemoved=function(e){return this.client.serverRemoved(e)},e.prototype.serverAdded=function(e){return this.client.serverAdded(e)},e.prototype.serverMethodRemoved=function(e){return this.client.serverMethodRemoved(e)},e.prototype.serverMethodAdded=function(e){return this.client.serverMethodAdded(e)},e.prototype.methodRemoved=function(e){return this.client.methodRemoved(e)},e.prototype.methodAdded=function(e){return this.client.methodAdded(e)},e.prototype.methodsForInstance=function(e){return this.client.methodsForInstance(e)},e.prototype.methods=function(e){return this.client.methods(e)},e.prototype.servers=function(e){return this.client.servers(e)},e.prototype.subscribe=function(e,t,n,i){return this.client.subscribe(e,t,n,i)},e.prototype.createStream=function(e,t,n,i){return this.server.createStream(e,t,n,i)},e.prototype.unregister=function(e){return this.server.unregister(e)},e.prototype.registerAsync=function(e,t){return this.server.registerAsync(e,t)},e.prototype.register=function(e,t){return this.server.register(e,t)},e.prototype.invoke=function(e,t,n,i,o,r){return this.client.invoke(e,t,n,i,o,r)},e.prototype.waitForMethod=function(e){var t=new Ni,n=this.client.methodAdded((function(i){i.name===e&&(n(),t.resolve(i))}));return t.promise},e}(),kr=["subscribed","success"],Mr=function(){function e(e,t){var n=this;this.publish=function(e,t,i){var o=i||{},r=o.routingKey,s=o.target,a=n.removeEmptyValues({type:"publish",topic:e,data:t,peer_id:n.peerId,routing_key:r,target_identity:s});n.session.send(a)},this.subscribe=function(e,t,i){return new Promise((function(o,r){var s=i||{},a=s.routingKey,c=s.target,u=n.removeEmptyValues({type:"subscribe",topic:e,peer_id:n.peerId,routing_key:a,source:c});n.session.send(u).then((function(i){var r=i.subscription_id;n.subscriptions.push({subscription_id:r,topic:e,callback:t,source:c}),o({unsubscribe:function(){return n.session.send({type:"unsubscribe",subscription_id:r,peer_id:n.peerId}),n.subscriptions=n.subscriptions.filter((function(e){return e.subscription_id!==r})),Promise.resolve()}})})).catch((function(e){return r(e)}))}))},this.watchOnEvent=function(){n.session.on("event",(function(e){var t=e.data,i=e.subscription_id,o=e["publisher-identity"],r=n.subscriptions.find((function(e){return e.subscription_id===i}));r&&(r.source?n.keysMatch(r.source,o)&&r.callback(t,r.topic,o):r.callback(t,r.topic,o))}))},this.connection=e,this.logger=t,this.peerId=e.peerId,this.subscriptions=[],this.session=e.domain("bus",kr),this.readyPromise=this.session.join(),this.readyPromise.then((function(){n.watchOnEvent()}))}return e.prototype.ready=function(){return this.readyPromise},e.prototype.removeEmptyValues=function(e){var t={};return Object.keys(e).forEach((function(n){void 0!==e[n]&&null!==e[n]&&(t[n]=e[n])})),t},e.prototype.keysMatch=function(e,t){var n=Object.keys(e),i=!0;return n.forEach((function(n){e[n]!==t[n]&&(i=!1)})),i},e}(),Rr=function(e,t){var n,i,o,r,s,a,c,u,d,h="object"==typeof window?null!==(n=window.iodesktop)&&void 0!==n?n:window.glue42gd:void 0,l="object"==typeof window&&null!==(i=window.gdPreloadPromise)&&void 0!==i?i:Promise.resolve(),p=Wi("glue"),f=function(e,t,n){var i,o,r,s,a;if(Oi.isNode()){var c=process.env._GD_STARTING_CONTEXT_;if(c)try{a=JSON.parse(c)}catch(e){}}function u(){if(e.application)return e.application;if(n)return n.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;var t=go();return Oi.isNode()?a?a.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+" (".concat(t,")"):t}var d=function(){var i,o,r,s,c,d,h,l,p,f,g,m=e.gateway,v=null!==(i=null==m?void 0:m.protocolVersion)&&void 0!==i?i:3,y=null==m?void 0:m.reconnectInterval,b=null==m?void 0:m.reconnectAttempts,w=null==m?void 0:m.ws,I=null==m?void 0:m.sharedWorker,C=null==m?void 0:m.inproc,S=null!==(o=null==m?void 0:m.webPlatform)&&void 0!==o?o:void 0;n&&(w=n.gwURL),Oi.isNode()&&a&&a.gwURL&&(w=a.gwURL),w||I||C||(w="ws://localhost:8385");var x=u(),_=x;void 0!==n?(l=n.windowId,p=n.pid,n.env&&(f=n.env.env,g=n.env.region),_=null!==(r=n.application)&&void 0!==r?r:"glue-app",h=n.appInstanceId):Oi.isNode()?(p=process.pid,a&&(f=a.env,g=a.region,h=a.instanceId)):void 0!==(null===window||void 0===window?void 0:window.glue42electron)&&(l=null===window||void 0===window?void 0:window.glue42electron.instanceId,p=null===window||void 0===window?void 0:window.glue42electron.pid,f=null===window||void 0===window?void 0:window.glue42electron.env,g=null===window||void 0===window?void 0:window.glue42electron.region,_=null!==(s=null===window||void 0===window?void 0:window.glue42electron.application)&&void 0!==s?s:"glue-app",h=null===window||void 0===window?void 0:window.glue42electron.instanceId);var P=null!==(d=null===(c=e.gateway)||void 0===c?void 0:c.replaySpecs)&&void 0!==d?d:[];P.push(Lo);var T={application:_,applicationName:x,windowId:l,instance:h,process:p,region:g,environment:f,api:t.version||qo};return e.identity&&(T=Object.assign(T,e.identity)),{identity:T,reconnectInterval:y,ws:w,sharedWorker:I,webPlatform:S,inproc:C,protocolVersion:v,reconnectAttempts:b,replaySpecs:P}}(),h=u();if("undefined"!=typeof window){var l=window,p=l.htmlContainer?"".concat(l.htmlContainer.containerName,".").concat(l.htmlContainer.application):null===(i=null==l?void 0:l.glue42gd)||void 0===i?void 0:i.application;p&&(h=p)}return{bus:null!==(o=e.bus)&&void 0!==o&&o,application:h,auth:function(){var t,n,i;return"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:Oi.isNode()&&a&&a.gwToken?{gatewayToken:a.gwToken}:(null===(t=e.gateway)||void 0===t?void 0:t.webPlatform)||(null===(n=e.gateway)||void 0===n?void 0:n.inproc)||(null===(i=e.gateway)||void 0===i?void 0:i.sharedWorker)?{username:"glue42",password:"glue42"}:void 0}(),logger:function(){var t,i,o,r=e.logger,s="warn";return r||(r=s),n&&(o=n.consoleLogLevel),"string"==typeof r?{console:null!=o?o:r,publish:s}:{console:null!==(t=null!=o?o:r.console)&&void 0!==t?t:s,publish:null!==(i=r.publish)&&void 0!==i?i:s}}(),connection:d,metrics:null===(r=e.metrics)||void 0===r||r,contexts:void 0===e.contexts||"boolean"==typeof e.contexts&&e.contexts?{reAnnounceKnownContexts:!0}:"object"==typeof e.contexts&&Object.assign({},{reAnnounceKnownContexts:!0},e.contexts),version:t.version||qo,libs:null!==(s=t.libs)&&void 0!==s?s:[],customLogger:e.customLogger}}(e=e||{},t=t||{},h),g={};function m(e,t,n){(d=s.canPublish("trace"))&&s.trace("registering ".concat(e," module"));var i=function(){t.initTime=n.stop(),t.initEndTime=n.endTime,t.marks=n.marks,d&&s.trace("".concat(e," is ready - ").concat(n.endTime-n.startTime))};t.initStartTime=n.startTime,t.ready?t.ready().then((function(){i()})):i(),Array.isArray(e)||(e=[e]),e.forEach((function(e){g[e]=t,Rr[e]=t}))}function v(){var e,t,n,i,r,c=Wi("metrics"),u=f.metrics,d=null==h?void 0:h.getMetricsPublishingEnabled,l=f.connection.identity,p=d||function(){return!0},g=null!==(e="boolean"!=typeof u&&u.disableAutoAppSystem)&&void 0!==e&&e;return m("metrics",a=Ti({connection:u?o:void 0,logger:s.subLogger("metrics"),canUpdateMetric:p,system:"Glue42",service:null!==(n=null!==(t=null==l?void 0:l.service)&&void 0!==t?t:null==h?void 0:h.applicationName)&&void 0!==n?n:f.application,instance:null!==(r=null!==(i=null==l?void 0:l.instance)&&void 0!==i?i:null==l?void 0:l.windowId)&&void 0!==r?r:go(),disableAutoAppSystem:g,pagePerformanceMetrics:"boolean"!=typeof u?null==u?void 0:u.pagePerformanceMetrics:void 0}),c),Promise.resolve()}function y(){var e=f.activities&&3===o.protocolVersion;if(f.contexts||e){var t=Wi("contexts");return m("contexts",c=new Yo({connection:o,logger:s.subLogger("contexts"),trackAllContexts:"object"==typeof f.contexts&&f.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof f.contexts&&f.contexts.reAnnounceKnownContexts}),t),c}var n=o.replayer;n&&n.drain(Lo.name)}function b(){return oi(this,void 0,void 0,(function(){var e;return ri(this,(function(t){return f.bus?(e=Wi("bus"),m("bus",u=new Mr(o,s.subLogger("bus")),e),[2,Promise.resolve()]):[2,Promise.resolve()]}))}))}function w(e){try{return e.forEach((function(e){!function(e,t){var n=Wi(e),i=t(g);i&&m(e,i,n)}(e.name,e.create)})),Promise.resolve()}catch(e){return Promise.reject(e)}}return l.then((function(){var e,t=Wi("logger");return(s=new xo("".concat(null===(e=f.connection.identity)||void 0===e?void 0:e.application),void 0,f.customLogger)).consoleLevel(f.logger.console),s.publishLevel(f.logger.publish),s.canPublish("debug")&&s.debug("initializing glue..."),m("logger",s,t),Promise.resolve(void 0)})).then((function(){var e=Wi("connection");o=new Co(f.connection,s.subLogger("connection"));var t=Promise.resolve(f.auth);return f.connection&&!f.auth&&(h?t=h.getGWToken().then((function(e){return{gatewayToken:e}})):"undefined"!=typeof window&&(null===window||void 0===window?void 0: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((function(t){var 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,o.login(n)})).then((function(){return m("connection",o,e),f})).catch((function(e){throw o&&o.logout(),e}))})).then((function(){return Promise.all([v(),(e=Wi("interop"),t={connection:o,logger:s.subLogger("interop")},r=new Tr(t),xo.Interop=r,m(["interop","agm"],r,e),Promise.resolve()),y(),b()]);var e,t})).then((function(){return r.readyPromise})).then((function(){return function(){return oi(this,void 0,void 0,(function(){var t,n,i;return ri(this,(function(o){switch(o.label){case 0:if(t="T42.ACS.RegisterInstance",!Oi.isNode()||void 0!==process.env._GD_STARTING_CONTEXT_||void 0===(null==e?void 0:e.application))return[3,4];if(!(r.methods({name:t}).length>0))return[3,4];o.label=1;case 1:return o.trys.push([1,3,,4]),[4,r.invoke(t,{appName:null==e?void 0:e.application,pid:process.pid})];case 2:return o.sent(),[3,4];case 3:return n=o.sent(),i=n,s.error("Cannot register as an instance: ".concat(JSON.stringify(i.message))),[3,4];case 4:return[2]}}))}))}()})).then((function(){return w(f.libs||[])})).then((function(){var e=Object.keys(g).map((function(e){var t=g[e];return t.ready?t.ready():Promise.resolve()}));return Promise.all(e)})).then((function(){var n={coreVersion:qo,version:f.version};p.stop();var i={feedback:function(e){r&&r.invoke("T42.ACS.Feedback",e,"best")},info:n,logger:s,interop:r,agm:r,connection:o,metrics:a,contexts:c,bus:u,version:f.version,userConfig:e,done:function(){return null==s||s.info("done called by user..."),o.logout()}};if(i.performance={get glueVer(){return f.version},get glueConfig(){return JSON.stringify(e)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){var e=Di;return Object.keys(e).map((function(t){var n=e[t];return{name:t,duration:n.endTime-n.startTime,marks:n.marks,startTime:n.startTime,endTime:n.endTime}}))}},Object.keys(g).forEach((function(e){var t=g[e];i[e]=t})),i.config={},Object.keys(f).forEach((function(e){i.config[e]=f[e]})),t&&t.extOptions&&Object.keys(t.extOptions).forEach((function(e){i.config[e]=null==t?void 0:t.extOptions[e]})),(null==t?void 0:t.enrichGlue)&&t.enrichGlue(i),h&&h.updatePerfData&&h.updatePerfData(i.performance),i.agm){var d=function(e,t,n){return function(){return i.logger.warn("glue.js - 'glue.agm.".concat(t,"' method is deprecated, use 'glue.interop.").concat(n,"' instead.")),e.apply(i.agm,arguments)}},l=i.agm;l.method_added=d(i.agm.methodAdded,"method_added","methodAdded"),l.method_removed=d(i.agm.methodRemoved,"method_removed","methodRemoved"),l.server_added=d(i.agm.serverAdded,"server_added","serverAdded"),l.server_method_aded=d(i.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),l.server_method_removed=d(i.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return i})).catch((function(e){return Promise.reject({err:e,libs:g})}))};"undefined"!=typeof window&&(window.IOConnectCore=Rr),Rr.version=qo,Rr.default=Rr;const jr=(Ar=Rr,e=>t(void 0,void 0,void 0,(function*(){if(window.glue42gd||window.iodesktop)return(e=>{var t,n,i;const o={windows:!0,layouts:"full",appManager:"full",channels:!0,libraries:null!==(t=null==e?void 0:e.libraries)&&void 0!==t?t:[],logger:null!==(i=null===(n=null==e?void 0:e.systemLogger)||void 0===n?void 0:n.level)&&void 0!==i?i:"warn"};return window.glue42gd,window.Glue(o)})(e);const t=new Zn,i=(e=>{var t,i,o;const r=!!(null===(i=null===(t=null==e?void 0:e.gateway)||void 0===t?void 0:t.webPlatform)||void 0===i?void 0:i.port),s=Object.assign({},n,e,{isPlatformInternal:r});return s.systemLogger&&(s.logger=null!==(o=s.systemLogger.level)&&void 0!==o?o:"info"),s})(e);(()=>{const e=window.glue42core||window.iobrowser;if(e&&e.webStarted)throw new Error("IoConnect Browser has already been started for this application.");e?e.webStarted=!0:window.iobrowser={webStarted:!0}})();const o=yield(r=()=>Ar(i,{version:ei}),s=3e4,a="Glue Web initialization timed out, because core didn't resolve",new Promise(((e,t)=>{let n=!0;const i=setTimeout((()=>{n&&(n=!1,t(a||`Promise timeout hit: ${s}`))}),s);r().then((t=>{n&&(n=!1,clearTimeout(i),e(t))})).catch((e=>{n&&(n=!1,clearTimeout(i),t(e))}))})));var r,s,a;const c=o.logger.subLogger("web.main.controller");return t.defineGlue(o),yield t.preferredConnectionController.start(i),yield t.bridge.start(t.controllers),t.defineConfig(i),c.trace("the bridge has been started, initializing all controllers"),yield Promise.all(Object.values(t.controllers).map((e=>e.start(o,t)))),c.trace("all controllers reported started, starting all additional libraries"),yield Promise.all(i.libraries.map((e=>e(o,i)))),c.trace("all libraries were started"),t.eventsDispatcher.start(o),c.trace("start event dispatched, glue is ready, returning it"),o})));var Ar;if("undefined"!=typeof window){const e=window;e.IOBrowser=jr,delete e.GlueCore,delete e.IOConnectCore}const Er=window.glue42gd||window.glue42core,Or=window.iodesktop||window.iobrowser;return Er||Or||(window.iobrowser={webStarted:!1}),jr.version=ei,jr}));
|
|
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,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 o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(n[i[o]]=e[i[o]])}return n}function t(e,t,n,i){return new(n||(n=Promise))((function(o,r){function s(e){try{c(i.next(e))}catch(e){r(e)}}function a(e){try{c(i.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))}const n={logger:"info",gateway:{webPlatform:{}},libraries:[],exposeAPI:!0};var i=function(e){return{ok:!0,result:e}},o=function(e){return{ok:!1,error:e}},r=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},s=function(e){if(!0===e.ok)return e.result;throw e.error},a=function(e,t){return!0===t.ok?i(e(t.result)):t},c=function(e,t,n){return!1===t.ok?t:!1===n.ok?n:i(e(t.result,n.result))},u=function(e,t){return!0===t.ok?t:o(e(t.error))},d=function(e,t){return!0===t.ok?e(t.result):t},h=function(){return h=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},h.apply(this,arguments)};function l(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(!l(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(!l(e[i[n]],t[i[n]]))return!1}return!0}}var p=function(e){return Array.isArray(e)},f=function(e){return"object"==typeof e&&null!==e&&!p(e)},g=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)},m=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 o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(n[i[o]]=e[i[o]])}return n}(t,["at"]);return h({at:e+(n||"")},i)},y=function(){function e(t){var n=this;this.decode=t,this.run=function(e){return u((function(t){return{kind:"DecoderError",input:e,at:"input"+(t.at||""),message:t.message||""}}),n.decode(e))},this.runPromise=function(e){return r(n.run(e))},this.runWithException=function(e){return s(n.run(e))},this.map=function(t){return new e((function(e){return a(t,n.decode(e))}))},this.andThen=function(t){return new e((function(e){return d((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?i(e):o({message:g("a string",e)})}))},e.number=function(){return new e((function(e){return"number"==typeof e?i(e):o({message:g("a number",e)})}))},e.boolean=function(){return new e((function(e){return"boolean"==typeof e?i(e):o({message:g("a boolean",e)})}))},e.constant=function(t){return new e((function(e){return l(e,t)?i(t):o({message:"expected "+JSON.stringify(t)+", got "+JSON.stringify(e)})}))},e.object=function(t){return new e((function(e){if(f(e)&&t){var n={};for(var r in t)if(t.hasOwnProperty(r)){var s=t[r].decode(e[r]);if(!0!==s.ok)return void 0===e[r]?o({message:"the key '"+r+"' is required but was not present"}):o(v("."+r,s.error));void 0!==s.result&&(n[r]=s.result)}return i(n)}return f(e)?i(e):o({message:g("an object",e)})}))},e.array=function(t){return new e((function(e){if(p(e)&&t){return e.reduce((function(e,n,i){return c((function(e,t){return e.concat([t])}),e,function(e,n){return u((function(e){return v("["+n+"]",e)}),t.decode(e))}(n,i))}),i([]))}return p(e)?i(e):o({message:g("an array",e)})}))},e.tuple=function(t){return new e((function(e){if(p(e)){if(e.length!==t.length)return o({message:"expected a tuple of length "+t.length+", got one of length "+e.length});for(var n=[],r=0;r<t.length;r++){var s=t[r].decode(e[r]);if(!s.ok)return o(v("["+r+"]",s.error));n[r]=s.result}return i(n)}return o({message:g("a tuple of length "+t.length,e)})}))},e.union=function(t,n){for(var i=[],o=2;o<arguments.length;o++)i[o-2]=arguments[o];return e.oneOf.apply(e,[t,n].concat(i))},e.intersection=function(t,n){for(var o=[],r=2;r<arguments.length;r++)o[r-2]=arguments[r];return new e((function(e){return[t,n].concat(o).reduce((function(t,n){return c(Object.assign,t,n.decode(e))}),i({}))}))},e.anyJson=function(){return new e((function(e){return i(e)}))},e.unknownJson=function(){return new e((function(e){return i(e)}))},e.dict=function(t){return new e((function(e){if(f(e)){var n={};for(var r in e)if(e.hasOwnProperty(r)){var s=t.decode(e[r]);if(!0!==s.ok)return o(v("."+r,s.error));n[r]=s.result}return i(n)}return o({message:g("an object",e)})}))},e.optional=function(t){return new e((function(e){return null==e?i(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 o({message:'expected a value matching one of the decoders, got the errors ["'+s+'"]'})}))},e.withDefault=function(t,n){return new e((function(e){return i(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 o({at:m(t.slice(0,r+1)),message:"path does not exist"});if("string"==typeof t[r]&&!f(i))return o({at:m(t.slice(0,r+1)),message:g("an object",i)});if("number"==typeof t[r]&&!p(i))return o({at:m(t.slice(0,r+1)),message:g("an array",i)});i=i[t[r]]}return u((function(e){return void 0===i?{at:m(t),message:"path does not exist"}:v(m(t),e)}),n.decode(i))}))},e.succeed=function(t){return new e((function(e){return i(t)}))},e.fail=function(t){return new e((function(e){return o({message:t})}))},e.lazy=function(t){return new e((function(e){return t().decode(e)}))},e}(),b=y.string,w=y.number,I=y.boolean,C=y.anyJson;y.unknownJson;var S=y.constant,x=y.object,_=y.array;y.tuple,y.dict;var P=y.optional,T=y.oneOf;y.union,y.intersection,y.withDefault,y.valueAt,y.succeed,y.fail;var k=y.lazy;const M=b().where((e=>e.length>0),"Expected a non-empty string"),R=w().where((e=>e>=0),"Expected a non-negative number"),j=T(S("system"),S("windows"),S("appManager"),S("layouts"),S("intents"),S("notifications"),S("channels"),S("extension"),S("themes")),A=T(S("openWindow"),S("windowHello"),S("windowAdded"),S("windowRemoved"),S("getBounds"),S("getFrameBounds"),S("getUrl"),S("moveResize"),S("focus"),S("close"),S("getTitle"),S("setTitle"),S("focusChange")),E=T(S("appHello"),S("appDirectoryStateChange"),S("instanceStarted"),S("instanceStopped"),S("applicationStart"),S("instanceStop"),S("clear")),O=T(S("layoutAdded"),S("layoutChanged"),S("layoutRemoved"),S("get"),S("getAll"),S("export"),S("import"),S("remove"),S("clientSaveRequest"),S("getGlobalPermissionState"),S("checkGlobalActivated"),S("requestGlobalPermission"),S("getDefaultGlobal"),S("setDefaultGlobal"),S("clearDefaultGlobal")),N=T(S("raiseNotification"),S("requestPermission"),S("notificationShow"),S("notificationClick"),S("getPermission"),S("list"),S("notificationRaised"),S("notificationClosed"),S("click"),S("clear"),S("clearAll")),D=T(S("getEnvironment"),S("getBase"),S("platformShutdown")),W=T(S("top"),S("left"),S("right"),S("bottom")),L=x({top:w(),left:w(),width:R,height:R}),q=P(x({top:P(w()),left:P(w()),width:P(R),height:P(R),context:P(C()),relativeTo:P(M),relativeDirection:P(W),windowId:P(M),layoutComponentId:P(M)})),F=x({name:M,url:M,options:q}),G=x({windowId:P(M)}),U=x({windowId:M,name:M}),B=x({windowId:M}),$=x({windows:_(U),isWorkspaceFrame:I()}),J=x({windowId:M,title:b()}),H=x({windowId:M,hasFocus:I()}),K=x({windowId:M,top:P(w()),left:P(w()),width:P(R),height:P(R),relative:P(I())}),V=x({windowId:M,bounds:x({top:w(),left:w(),width:R,height:R})}),z=x({bounds:x({top:w(),left:w(),width:R,height:R})}),Q=x({windowId:M,url:M}),X=C(),Y=x({top:P(w()),left:P(w()),width:P(R),height:P(R)}),Z=x({id:M,applicationName:M}),ee=x({url:M,top:P(w()),left:P(w()),width:P(R),height:P(R)}),te=x({name:M,displayName:P(b()),contexts:P(_(b())),customConfig:P(x())}),ne=x({name:M,title:P(M),version:P(M),appId:P(M),manifest:M,manifestType:M,tooltip:P(M),description:P(M),contactEmail:P(M),supportEmail:P(M),publisher:P(M),images:P(_(x({url:P(M)}))),icons:P(_(x({icon:P(M)}))),customConfig:C(),intents:P(_(te))}),ie=x({name:M,type:M.where((e=>"window"===e),"Expected a value of window"),title:P(M),version:P(M),customProperties:P(C()),icon:P(b()),caption:P(b()),details:ee,intents:P(_(te)),hidden:P(I())}),oe=T(ie,ne);x({definitions:_(oe),mode:T(S("replace"),S("merge"))});const re=x({name:M}),se=x({definitions:_(ie)}),ae=x({name:M,type:M.where((e=>"window"===e),"Expected a value of window"),instances:_(Z),userProperties:P(C()),title:P(M),version:P(M),icon:P(M),caption:P(M)}),ce=x({name:M,type:M.where((e=>"window"===e),"Expected a value of window"),userProperties:C(),title:P(M),version:P(M),icon:P(M),caption:P(M)}),ue=x({appsAdded:_(ce),appsChanged:_(ce),appsRemoved:_(ce)}),de=x({apps:_(ae)}),he=x({id:M}),le=x({name:M,waitForAGMReady:I(),id:P(M),context:P(C()),top:P(w()),left:P(w()),width:P(R),height:P(R),relativeTo:P(M),relativeDirection:P(T(S("top"),S("left"),S("right"),S("bottom"))),forceChromeTab:P(I()),layoutComponentId:P(M)}),pe=T(S("Global"),S("Activity"),S("ApplicationDefault"),S("Swimlane"),S("Workspace")),fe=T(S("application"),S("activity")),ge=x({context:P(C()),bounds:L,createArgs:x({name:P(M),url:P(M),context:P(C())}),windowState:P(M),restoreState:P(M),instanceId:M,isCollapsed:P(I()),isSticky:P(I()),restoreSettings:x({groupId:P(M),groupZOrder:P(w())})}),me=x({type:S("window"),componentType:P(fe),application:M,state:ge}),ve=x({type:S("window"),config:x({appName:M,url:P(M),title:P(b()),allowExtract:P(I()),allowReorder:P(I()),showCloseButton:P(I()),isMaximized:P(I())})}),ye=x({type:S("group"),config:C(),children:_(T(ve))}),be=x({type:S("column"),config:C(),children:_(T(ye,ve,k((()=>be)),k((()=>we))))}),we=x({type:S("row"),config:C(),children:_(T(be,ye,ve,k((()=>we))))}),Ie=x({config:C(),context:C(),children:_(T(we,be,ye,ve))}),Ce=x({type:S("Workspace"),application:P(M),state:Ie}),Se=x({bounds:L,instanceId:M,selectedWorkspace:R,workspaces:_(Ie),windowState:P(M),restoreState:P(M),context:P(C())}),xe=x({type:S("workspaceFrame"),application:M,componentType:P(fe),state:Se}),_e=x({name:M,type:pe,components:_(T(me,Ce,xe)),context:P(C()),metadata:P(C()),version:P(w())}),Pe=x({name:M,context:P(C()),metadata:P(C()),instances:P(_(M)),ignoreInstances:P(_(M))}),Te=x({name:M,context:P(C()),closeRunningInstance:P(I()),closeMe:P(I()),timeout:P(R)}),ke=x({name:M,type:pe,context:P(C()),metadata:P(C())}),Me=x({name:M,type:pe}),Re=x({layout:Pe}),je=x({layout:Te}),Ae=x({type:pe}),Ee=x({layouts:_(_e)}),Oe=T(S("replace"),S("merge")),Ne=x({layouts:_(_e),mode:Oe,isManagerOperation:P(I())}),De=x({summaries:_(ke)}),We=x({layout:_e}),Le=x({layout:P(_e)}),qe=x({name:M}),Fe=T(S("findIntent"),S("getIntents"),S("raiseIntent"),S("raise")),Ge=x({applicationName:M,applicationTitle:P(b()),applicationDescription:P(b()),applicationIcon:P(b()),type:T(S("app"),S("instance")),displayName:P(b()),contextTypes:P(_(M)),instanceId:P(b()),instanceTitle:P(b()),resultType:P(b())});x({applicationName:b(),applicationIcon:P(b()),instanceId:P(b())});const Ue=x({intent:M,handler:Ge}),Be=x({name:M,handlers:_(Ge)}),$e=T(S("startNew"),S("reuse"),x({app:P(M),instance:P(M)})),Je=x({type:P(M),data:P(C())}),He=x({intents:_(Be)}),Ke=x({name:P(M),contextType:P(M),resultType:P(M)}),Ve=T(M,Ke),ze=x({filter:P(Ke)}),Qe=x({intent:M,target:P($e),context:P(Je),options:P(q),handlers:P(_(Ge)),timeout:P(R),waitUserResponseIndefinitely:P(I())}),Xe=T(M,Qe),Ye=x({enabled:I(),appName:M,waitResponseTimeout:w()}),Ze=x({intentRequest:Qe,resolverConfig:Ye}),et=x({request:Qe,handler:Ge,result:C()}),tt=x({intent:M,contextTypes:P(_(M)),displayName:P(b()),icon:P(b()),description:P(b()),resultType:P(b())}),nt=T(M,tt),it=e=>M.where((t=>e.includes(t)),"Expected a valid channel name"),ot=x({method:M,arguments:P(C()),target:P(T(S("all"),S("best")))}),rt=x({action:b(),title:M,icon:P(b()),interop:P(ot)}),st=x({badge:P(b()),body:P(b()),data:P(C()),dir:P(T(S("auto"),S("ltr"),S("rtl"))),icon:P(b()),image:P(b()),lang:P(b()),renotify:P(I()),requireInteraction:P(I()),silent:P(I()),tag:P(b()),timestamp:P(R),vibrate:P(_(w()))}),at=x({title:M,clickInterop:P(ot),actions:P(_(rt)),focusPlatformOnDefaultClick:P(I()),badge:P(b()),body:P(b()),data:P(C()),dir:P(T(S("auto"),S("ltr"),S("rtl"))),icon:P(b()),image:P(b()),lang:P(b()),renotify:P(I()),requireInteraction:P(I()),silent:P(I()),tag:P(b()),timestamp:P(R),vibrate:P(_(w())),severity:P(T(S("Low"),S("None"),S("Medium"),S("High"),S("Critical"))),showToast:P(I()),showInPanel:P(I())}),ct=x({name:M,meta:x({color:M}),data:P(x())}),ut=x({settings:at,id:M}),dt=x({settings:at}),ht=x({permissionGranted:I()}),lt=x({permission:T(S("default"),S("granted"),S("denied"))}),pt=x({definition:st,action:P(b()),id:P(M)}),ft=x({layoutType:T(S("Global"),S("Workspace")),layoutName:M,context:P(C())}),gt=x({windowContext:P(C())}),mt=x({state:T(S("prompt"),S("denied"),S("granted"))}),vt=x({isAvailable:I()}),yt=x({itemId:M}),bt=x({isSupported:I()}),wt=x({operation:M}),It=x({bounds:L}),Ct=x({displayName:M,name:M}),St=x({theme:Ct}),xt=x({themes:_(Ct)}),_t=x({name:M}),Pt=x({id:M,title:M,clickInterop:P(ot),actions:P(_(rt)),focusPlatformOnDefaultClick:P(I()),badge:P(b()),body:P(b()),data:P(C()),dir:P(T(S("auto"),S("ltr"),S("rtl"))),icon:P(b()),image:P(b()),lang:P(b()),renotify:P(I()),requireInteraction:P(I()),silent:P(I()),tag:P(b()),timestamp:P(R),vibrate:P(_(w())),severity:P(T(S("Low"),S("None"),S("Medium"),S("High"),S("Critical"))),showToast:P(I()),showInPanel:P(I())}),Tt=x({notification:Pt}),kt=x({notifications:_(Pt)}),Mt=x({id:M}),Rt={openWindow:{name:"openWindow",dataDecoder:F,resultDecoder:U},windowHello:{name:"windowHello",dataDecoder:G,resultDecoder:$},windowAdded:{name:"windowAdded",dataDecoder:U},windowRemoved:{name:"windowRemoved",dataDecoder:B},getBounds:{name:"getBounds",dataDecoder:B,resultDecoder:V},getFrameBounds:{name:"getFrameBounds",dataDecoder:B,resultDecoder:z},getUrl:{name:"getUrl",dataDecoder:B,resultDecoder:Q},moveResize:{name:"moveResize",dataDecoder:K},focus:{name:"focus",dataDecoder:B},close:{name:"close",dataDecoder:B},getTitle:{name:"getTitle",dataDecoder:B,resultDecoder:J},setTitle:{name:"setTitle",dataDecoder:J},focusChange:{name:"focusChange",dataDecoder:H}};function jt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function At(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 o=n instanceof Error?n:new Error(n);if(t)t(o);else{var r='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+o.stack;if(e)switch(e.errorHandling){case"log":return console.error(r);case"silent":return;case"throw":throw new Error(r)}console.error(r)}}return{add:function(e,t,o){var r=n[e];return r||(r=[],n[e]=r),r.push(t),o&&setTimeout((function(){o.forEach((function(o){var r;if(null===(r=n[e])||void 0===r?void 0:r.includes(t))try{Array.isArray(o)?t.apply(void 0,o):t.apply(void 0,[o])}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=[],o=1;o<arguments.length;o++)t[o-1]=arguments[o];var r=n[e];if(!r||0===r.length)return[];var s=[];return r.forEach((function(n){try{var o=n.apply(void 0,t);s.push(o)}catch(t){s.push(void 0),i(t,e)}})),s},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}At.default=At;var Et=At;class Ot{constructor(e,t,n){this._id=e,this._name=t,this._bridge=n,this.registry=Et(),this.myCtxKey=`___window___${this.id}`}get id(){return this._id.slice()}get name(){return this._name.slice()}clean(){this.ctxUnsubscribe&&this.ctxUnsubscribe()}processSelfFocusEvent(e){this.me.isFocused=e,this.registry.execute("focus-change",this.me)}toApi(){return t(this,void 0,void 0,(function*(){return this.ctxUnsubscribe=yield this._bridge.contextLib.subscribe(this.myCtxKey,(e=>this.registry.execute("context-updated",e))),this.me={id:this.id,name:this.name,isFocused:!1,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),onContextUpdated:this.onContextUpdated.bind(this),onFocusChanged:this.onFocusChanged.bind(this)},this.me}))}getURL(){return t(this,void 0,void 0,(function*(){return(yield this._bridge.send("windows",Rt.getUrl,{windowId:this.id})).url}))}onFocusChanged(e){if("function"!=typeof e)throw new Error("Cannot subscribe to context changes, because the provided callback is not a function!");return this.registry.add("focus-change",e)}moveResize(e){return t(this,void 0,void 0,(function*(){const t=Y.runWithException(e),n=Object.assign({},t,{windowId:this.id,relative:!1});return yield this._bridge.send("windows",Rt.moveResize,n),this.me}))}resizeTo(e,n){return t(this,void 0,void 0,(function*(){if(void 0===e&&void 0===n)return this.me;void 0!==e&&R.runWithException(e),void 0!==n&&R.runWithException(n);const t=Object.assign({},{width:e,height:n},{windowId:this.id,relative:!0});return yield this._bridge.send("windows",Rt.moveResize,t),this.me}))}moveTo(e,n){return t(this,void 0,void 0,(function*(){if(void 0===e&&void 0===n)return this.me;void 0!==e&&w().runWithException(e),void 0!==n&&w().runWithException(n);const t=Object.assign({},{top:e,left:n},{windowId:this.id,relative:!0});return yield this._bridge.send("windows",Rt.moveResize,t),this.me}))}focus(){return t(this,void 0,void 0,(function*(){return"Platform"===this.name?window.open(void 0,this.id):yield this._bridge.send("windows",Rt.focus,{windowId:this.id}),this.me}))}close(){return t(this,void 0,void 0,(function*(){return yield this._bridge.send("windows",Rt.close,{windowId:this.id}),this.me}))}getTitle(){return t(this,void 0,void 0,(function*(){return(yield this._bridge.send("windows",Rt.getTitle,{windowId:this.id})).title}))}setTitle(e){return t(this,void 0,void 0,(function*(){const t=M.runWithException(e);return yield this._bridge.send("windows",Rt.setTitle,{windowId:this.id,title:t}),this.me}))}getBounds(){return t(this,void 0,void 0,(function*(){return(yield this._bridge.send("windows",Rt.getBounds,{windowId:this.id})).bounds}))}getContext(){return t(this,void 0,void 0,(function*(){return yield this._bridge.contextLib.get(this.myCtxKey)}))}updateContext(e){return t(this,void 0,void 0,(function*(){const t=X.runWithException(e);return yield this._bridge.contextLib.update(this.myCtxKey,t),this.me}))}setContext(e){return t(this,void 0,void 0,(function*(){const t=X.runWithException(e);return yield this._bridge.contextLib.set(this.myCtxKey,t),this.me}))}onContextUpdated(e){if("function"!=typeof e)throw new Error("Cannot subscribe to context changes, because the provided callback is not a function!");return this.registry.add("context-updated",(t=>{e(t,this.me)}))}}const Nt={operationCheck:{name:"operationCheck",dataDecoder:wt,resultDecoder:bt},getWorkspaceWindowFrameBounds:{name:"getWorkspaceWindowFrameBounds",resultDecoder:It,dataDecoder:yt}},Dt=(e,t,n)=>new Promise(((i,o)=>{const r=setTimeout((()=>{o(n||`Promise timeout hit: ${t}`)}),t);new Promise(e).then((e=>{clearTimeout(r),i(e)})).catch((e=>{clearTimeout(r),o(e)}))}));class Wt{constructor(){this.registry=Et(),this.allWindowProjections=[]}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("windows.controller.web"),this.logger.trace("starting the web windows controller"),this.publicWindowId=n.publicWindowId,this.addWindowOperationExecutors(),this.ioc=n,this.bridge=n.bridge,this.instanceId=e.interop.instance.instance,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(),yield this.platformRegistration,yield this.initializeFocusTracking(),this.logger.trace("registration with the platform successful, attaching the windows property to glue and returning");const t=this.toApi();e.windows=t}))}handlePlatformShutdown(){this.registry.clear(),this.allWindowProjections=[],this.focusEventHandler&&(document.removeEventListener("visibilityChange",this.focusEventHandler),window.removeEventListener("focus",this.focusEventHandler),window.removeEventListener("blur",this.focusEventHandler))}handleBridgeMessage(e){return t(this,void 0,void 0,(function*(){yield this.platformRegistration;const t=A.runWithException(e.operation),n=Rt[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=n.dataDecoder.runWithException(e.data)),yield n.execute(i)}))}open(e,n,i){return t(this,void 0,void 0,(function*(){M.runWithException(e),M.runWithException(n);const t=q.runWithException(i),o=yield this.bridge.send("windows",Rt.openWindow,{name:e,url:n,options:t});return this.waitForWindowAdded(o.windowId)}))}list(){return this.allWindowProjections.map((e=>e.api))}findById(e){var t;return M.runWithException(e),null===(t=this.allWindowProjections.find((t=>t.id===e)))||void 0===t?void 0:t.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(){Rt.focusChange.execute=this.handleFocusChangeEvent.bind(this),Rt.windowAdded.execute=this.handleWindowAdded.bind(this),Rt.windowRemoved.execute=this.handleWindowRemoved.bind(this),Rt.getBounds.execute=this.handleGetBounds.bind(this),Rt.getFrameBounds.execute=this.handleGetBounds.bind(this),Rt.getTitle.execute=this.handleGetTitle.bind(this),Rt.getUrl.execute=this.handleGetUrl.bind(this),Rt.moveResize.execute=this.handleMoveResize.bind(this),Rt.setTitle.execute=this.handleSetTitle.bind(this)}my(){return Object.assign({},this.me)}onWindowAdded(e){if("function"!=typeof e)throw new Error("Cannot subscribe to window added, because the provided callback is not a function!");return this.registry.add("window-added",e)}onWindowRemoved(e){if("function"!=typeof e)throw new Error("Cannot subscribe to window removed, because the provided callback is not a function!");return this.registry.add("window-removed",e)}onWindowGotFocus(e){if("function"!=typeof e)throw new Error("Cannot subscribe to onWindowGotFocus, because the provided callback is not a function!");return this.registry.add("window-got-focus",e)}onWindowLostFocus(e){if("function"!=typeof e)throw new Error("Cannot subscribe to onWindowLostFocus, because the provided callback is not a function!");return this.registry.add("window-lost-focus",e)}sayHello(){return t(this,void 0,void 0,(function*(){return yield this.bridge.send("windows",Rt.windowHello,{windowId:this.publicWindowId})}))}registerWithPlatform(){return t(this,void 0,void 0,(function*(){const{windows:e,isWorkspaceFrame:t}=yield 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)throw new Error("Cannot initialize the window library, because I received no information about me from the platform");const n=yield this.ioc.buildWebWindow(this.publicWindowId,t.name);this.me=n.api,this.allWindowProjections.push(n)}const n=yield Promise.all(e.filter((e=>e.windowId!==this.publicWindowId)).map((e=>this.ioc.buildWebWindow(e.windowId,e.name))));this.logger.trace("all windows projections are completed, building the list collection"),this.allWindowProjections.push(...n)}))}handleFocusChangeEvent(e){return t(this,void 0,void 0,(function*(){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)}))}handleWindowAdded(e){return t(this,void 0,void 0,(function*(){if(this.allWindowProjections.some((t=>t.id===e.windowId)))return;const t=yield this.ioc.buildWebWindow(e.windowId,e.name);this.allWindowProjections.push(t),this.registry.execute("window-added",t.api)}))}handleWindowRemoved(e){return t(this,void 0,void 0,(function*(){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))}))}handleGetBounds(){return t(this,void 0,void 0,(function*(){if(!this.me&&!this.isWorkspaceFrame)throw new Error("This window cannot report it's bounds, because it is not a Glue Window, most likely because it is an iframe");return{windowId:this.isWorkspaceFrame?"noop":this.me.id,bounds:{top:window.screenTop,left:window.screenLeft,width:window.innerWidth,height:window.innerHeight}}}))}handleGetTitle(){return t(this,void 0,void 0,(function*(){if(!this.me)throw new Error("This window cannot report it's title, because it is not a Glue Window, most likely because it is an iframe");return{windowId:this.me.id,title:document.title}}))}handleGetUrl(){return t(this,void 0,void 0,(function*(){if(!this.me)throw new Error("This window cannot report it's url, because it is not a Glue Window, most likely because it is an iframe");return{windowId:this.me.id,url:window.location.href}}))}handleMoveResize(e){return t(this,void 0,void 0,(function*(){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,o="number"==typeof e.width?e.width:e.relative?0:window.innerWidth,r=e.relative?window.moveBy:window.moveTo,s=e.relative?window.resizeBy:window.resizeTo;r(n,t),s(o,i)}))}handleSetTitle(e){return t(this,void 0,void 0,(function*(){document.title=e.title}))}initializeFocusTracking(){return t(this,void 0,void 0,(function*(){if(this.isWorkspaceFrame)return void this.logger.trace("Ignoring the focus tracking, because this client is a workspace frame");try{yield this.bridge.send("windows",Nt.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();yield this.transmitFocusChange(!0),e||(yield 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):Dt((t=>{const n=this.onWindowAdded((i=>{i.id===e&&(n(),t(i))}))}),3e4,`Timed out waiting for ${e} to be announced`)}transmitFocusChange(e){var n;return t(this,void 0,void 0,(function*(){const t={windowId:(null===(n=this.me)||void 0===n?void 0:n.id)||`iframe-${this.instanceId}`,hasFocus:e};this.me&&(this.me.isFocused=e),yield this.bridge.send("windows",Rt.focusChange,t)}))}defineEventListeners(){this.focusEventHandler=this.processFocusEvent.bind(this),document.addEventListener("visibilityChange",this.focusEventHandler),window.addEventListener("focus",this.focusEventHandler),window.addEventListener("blur",this.focusEventHandler)}}const Lt="T42.Web.Platform.Control",qt="T42.Web.Platform.Stream",Ft="T42.Web.Client.Control",Gt="T42.Core.Plus.Themes.Stream";class Ut{constructor(e,t){this.coreGlue=e,this.communicationId=t,this.platformMethodTimeoutMs=1e4}get contextLib(){return this.coreGlue.contexts}get interopInstance(){return this.coreGlue.interop.instance.instance}stop(){return t(this,void 0,void 0,(function*(){this.running=!1,this.sub.close(),yield this.coreGlue.interop.unregister(Ft)}))}start(e){return t(this,void 0,void 0,(function*(){this.running=!0,this.controllers=e,yield Promise.all([this.checkWaitMethod(Lt),this.checkWaitMethod(qt)]);const t=this.communicationId,[n]=yield Promise.all([this.coreGlue.interop.subscribe(qt,t?{target:{instance:this.communicationId}}:void 0),this.coreGlue.interop.registerAsync(Ft,((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:null==t?void 0:t.application,applicationName:null==t?void 0:t.applicationName,peerId:null==t?void 0:t.peerId,instance:null==t?void 0:t.instance,windowId:null==t?void 0:t.windowId}}send(e,n,i,o,r){return t(this,void 0,void 0,(function*(){if(n.dataDecoder)try{n.dataDecoder.runWithException(i)}catch(e){throw new Error(`Unexpected Web->Platform outgoing validation error: ${e.message}, for operation: ${n.name} and input: ${JSON.stringify(e.input)}`)}if(!(!(null==r?void 0:r.includeOperationCheck)||(yield this.checkOperationSupported(e,n)).isSupported))throw new Error(`Cannot complete operation: ${n.name} for domain: ${e} because this client is connected to a platform which does not support it`);try{const t=yield this.transmitMessage(e,n,i,o);return n.resultDecoder&&n.resultDecoder.runWithException(t),t}catch(e){if(e.kind)throw new Error(`Unexpected Web<-Platform incoming validation error: ${e.message}, for operation: ${n.name} and input: ${JSON.stringify(e.input)}`);throw new Error(e.message)}}))}createNotificationsSteam(){return t(this,void 0,void 0,(function*(){if(!this.coreGlue.interop.methods().some((e=>e.name===Gt)))throw new Error("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.");return this.coreGlue.interop.subscribe(Gt,this.communicationId?{target:{instance:this.communicationId}}:void 0)}))}checkOperationSupported(e,n){return t(this,void 0,void 0,(function*(){try{return yield this.send(e,Nt.operationCheck,{operation:n.name})}catch(e){return{isSupported:!1}}}))}checkWaitMethod(e){return Dt((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 o=i.method,r=i.server,s=!this.communicationId||r.instance===this.communicationId;o.name===e&&s&&(n(),t())}))}),this.platformMethodTimeoutMs,`Cannot initiate Glue Web, because a system method's discovery timed out: ${e}`)}passMessageController(e,t,n){const i=j.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 o=i.result;this.controllers[o].handleBridgeMessage(e).then((e=>{t&&t(e)})).catch((e=>{n&&n(e),console.warn(e)}))}transmitMessage(e,n,i,o){return t(this,void 0,void 0,(function*(){const t={domain:e,data:i,operation:n.name};let r;const s=`Internal Platform Communication Error. Attempted operation: ${JSON.stringify(n.name)} with data: ${JSON.stringify(i)}. `,a=this.communicationId;try{if(!this.running)throw new Error("Cannot send a control message, because the platform shut down");if(r=yield this.coreGlue.interop.invoke(Lt,t,a?{instance:this.communicationId}:void 0,o),!r)throw new Error("Received unsupported result from the platform - empty result");if(!Array.isArray(r.all_return_values)||0===r.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(`${s} -> Inner message: ${t}`)}throw new Error(`${s} -> Inner message: ${e.message}`)}return r.all_return_values[0].returned}))}}const Bt={appHello:{name:"appHello",dataDecoder:G,resultDecoder:de},appDirectoryStateChange:{name:"appDirectoryStateChange",dataDecoder:ue},instanceStarted:{name:"instanceStarted",dataDecoder:Z},instanceStopped:{name:"instanceStopped",dataDecoder:Z},applicationStart:{name:"applicationStart",dataDecoder:le,resultDecoder:Z},instanceStop:{name:"instanceStop",dataDecoder:he},import:{name:"import"},remove:{name:"remove",dataDecoder:re},export:{name:"export",resultDecoder:se},clear:{name:"clear"}};class $t{constructor(){this.baseApplicationsTimeoutMS=6e4,this.appImportTimeoutMS=20,this.registry=Et(),this.applications=[],this.instances=[]}handlePlatformShutdown(){this.registry.clear(),this.applications=[],this.instances=[],delete this.me}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("appManger.controller.web"),this.logger.trace("starting the web appManager controller"),this.publicWindowId=n.publicWindowId,this.addOperationsExecutors(),this.ioc=n,this.bridge=n.bridge,this.platformRegistration=this.registerWithPlatform(),yield this.platformRegistration,this.logger.trace("registration with the platform successful, attaching the appManager property to glue and returning");const t=this.toApi();e.appManager=t}))}handleBridgeMessage(e){return t(this,void 0,void 0,(function*(){yield this.platformRegistration;const t=E.runWithException(e.operation),n=Bt[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=n.dataDecoder.runWithException(e.data)),yield n.execute(i)}))}onInstanceStarted(e){if("function"!=typeof e)throw new Error("onInstanceStarted requires a single argument of type function");return this.registry.add("instance-started",e,this.instances)}onInstanceStopped(e){if("function"!=typeof e)throw new Error("onInstanceStopped requires a single argument of type function");return this.registry.add("instance-stopped",e)}startApplication(e,n,i){var o;return t(this,void 0,void 0,(function*(){const t={name:e,waitForAGMReady:null===(o=null==i?void 0:i.waitForAGMReady)||void 0===o||o,context:n,top:null==i?void 0:i.top,left:null==i?void 0:i.left,width:null==i?void 0:i.width,height:null==i?void 0:i.height,relativeTo:null==i?void 0:i.relativeTo,relativeDirection:null==i?void 0:i.relativeDirection,id:null==i?void 0:i.reuseId,forceChromeTab:null==i?void 0:i.forceTab,layoutComponentId:null==i?void 0:i.layoutComponentId},r=yield this.bridge.send("appManager",Bt.applicationStart,t),s=this.applications.find((e=>e.name===r.applicationName));return this.ioc.buildInstance(r,s)}))}getApplication(e){const t=M.runWithException(e);return this.applications.find((e=>e.name===t))}getInstances(){return this.instances.slice()}toApi(){return{myInstance:this.me,inMemory:{import:this.import.bind(this),remove:this.remove.bind(this),export:this.export.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(){Bt.appDirectoryStateChange.execute=this.handleAppDirectoryStateChange.bind(this),Bt.instanceStarted.execute=this.handleInstanceStartedMessage.bind(this),Bt.instanceStopped.execute=this.handleInstanceStoppedMessage.bind(this)}handleAppDirectoryStateChange(e){return t(this,void 0,void 0,(function*(){e.appsAdded.forEach(this.handleApplicationAddedMessage.bind(this)),e.appsChanged.forEach(this.handleApplicationChangedMessage.bind(this)),e.appsRemoved.forEach(this.handleApplicationRemovedMessage.bind(this))}))}onAppAdded(e){if("function"!=typeof e)throw new Error("onAppAdded requires a single argument of type function");return this.registry.add("application-added",e,this.applications)}onAppRemoved(e){if("function"!=typeof e)throw new Error("onAppRemoved requires a single argument of type function");return this.registry.add("application-removed",e)}onAppChanged(e){if("function"!=typeof e)throw new Error("onAppChanged requires a single argument of type function");return this.registry.add("application-changed",e)}handleApplicationAddedMessage(e){return t(this,void 0,void 0,(function*(){if(this.applications.some((t=>t.name===e.name)))return;const t=yield 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)}))}handleApplicationRemovedMessage(e){return t(this,void 0,void 0,(function*(){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)}))}handleApplicationChangedMessage(e){return t(this,void 0,void 0,(function*(){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)}))}handleInstanceStartedMessage(e){return t(this,void 0,void 0,(function*(){if(this.instances.some((t=>t.id===e.id)))return;const t=this.applications.find((t=>t.name===e.applicationName));if(!t)throw new Error(`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)}))}handleInstanceStoppedMessage(e){return t(this,void 0,void 0,(function*(){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)}))}import(e,n="replace"){return t(this,void 0,void 0,(function*(){if(Oe.runWithException(n),!Array.isArray(e))throw new Error("Import must be called with an array of definitions");if(e.length>1e4)throw new Error("Cannot import more than 10000 app definitions in Glue42 Core.");const t=e.reduce(((e,t)=>{const n=oe.run(t);return n.ok?e.valid.push(t):e.invalid.push({app:null==t?void 0:t.name,error:JSON.stringify(n.error)}),e}),{valid:[],invalid:[]}),i=this.baseApplicationsTimeoutMS+this.appImportTimeoutMS*t.valid.length;return yield this.bridge.send("appManager",Bt.import,{definitions:t.valid,mode:n},{methodResponseTimeoutMs:i}),{imported:t.valid.map((e=>e.name)),errors:t.invalid}}))}remove(e){return t(this,void 0,void 0,(function*(){M.runWithException(e),yield this.bridge.send("appManager",Bt.remove,{name:e},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}))}clear(){return t(this,void 0,void 0,(function*(){yield this.bridge.send("appManager",Bt.clear,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}))}export(){return t(this,void 0,void 0,(function*(){return(yield this.bridge.send("appManager",Bt.export,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})).definitions}))}getApplications(){return this.applications.slice()}registerWithPlatform(){return t(this,void 0,void 0,(function*(){const e=yield this.bridge.send("appManager",Bt.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=yield 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`)}))}findMyInstance(){for(const e of this.applications){const t=e.instances.find((e=>e.id===this.publicWindowId));if(t)return t}}}class Jt{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}getContext(){return t(this,void 0,void 0,(function*(){return this.bridge.contextLib.get(this.myCtxKey)}))}stop(){return t(this,void 0,void 0,(function*(){yield this.bridge.send("appManager",Bt.instanceStop,{id:this.data.id})}))}}class Ht{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),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)};return this.me=e,this.me}onInstanceStarted(e){if("function"!=typeof e)throw new Error("OnInstanceStarted requires a single argument of type function");return this.controller.onInstanceStarted((t=>{t.application.name===this.data.name&&e(t)}))}onInstanceStopped(e){if("function"!=typeof e)throw new Error("OnInstanceStarted requires a single argument of type function");return this.controller.onInstanceStopped((t=>{t.application.name===this.data.name&&e(t)}))}start(e,n){return t(this,void 0,void 0,(function*(){return this.controller.startApplication(this.data.name,e,n)}))}}const Kt={layoutAdded:{name:"layoutAdded",dataDecoder:_e},layoutChanged:{name:"layoutChanged",dataDecoder:_e},layoutRemoved:{name:"layoutRemoved",dataDecoder:_e},get:{name:"get",dataDecoder:Me,resultDecoder:Le},getAll:{name:"getAll",dataDecoder:Ae,resultDecoder:De},export:{name:"export",dataDecoder:Ae,resultDecoder:Ee},import:{name:"import",dataDecoder:Ne},remove:{name:"remove",dataDecoder:Me},save:{name:"save",dataDecoder:Re,resultDecoder:We},restore:{name:"restore",dataDecoder:je},clientSaveRequest:{name:"clientSaveRequest",dataDecoder:ft,resultDecoder:gt},getGlobalPermissionState:{name:"getGlobalPermissionState",resultDecoder:mt},requestGlobalPermission:{name:"requestGlobalPermission",resultDecoder:vt},checkGlobalActivated:{name:"checkGlobalActivated",resultDecoder:vt},getDefaultGlobal:{name:"getDefaultGlobal",resultDecoder:Le},setDefaultGlobal:{name:"setDefaultGlobal",dataDecoder:qe},clearDefaultGlobal:{name:"clearDefaultGlobal"}};class Vt{constructor(){this.defaultLayoutRestoreTimeoutMS=12e4,this.registry=Et()}handlePlatformShutdown(){this.registry.clear()}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("layouts.controller.web"),this.logger.trace("starting the web layouts controller"),this.bridge=n.bridge,this.windowsController=n.windowsController,this.addOperationsExecutors();const t=this.toApi();this.logger.trace("no need for platform registration, attaching the layouts property to glue and returning"),e.layouts=t}))}handleBridgeMessage(e){return t(this,void 0,void 0,(function*(){const t=O.runWithException(e.operation),n=Kt[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=n.dataDecoder.runWithException(e.data)),yield n.execute(i)}))}toApi(){const e={get:this.get.bind(this),getAll:this.getAll.bind(this),export:this.export.bind(this),import:this.import.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),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)};return Object.freeze(e)}addOperationsExecutors(){Kt.layoutAdded.execute=this.handleOnAdded.bind(this),Kt.layoutChanged.execute=this.handleOnChanged.bind(this),Kt.layoutRemoved.execute=this.handleOnRemoved.bind(this),Kt.clientSaveRequest.execute=this.handleSaveRequest.bind(this)}get(e,n){return t(this,void 0,void 0,(function*(){M.runWithException(e),pe.runWithException(n);return(yield this.bridge.send("layouts",Kt.get,{name:e,type:n})).layout}))}getAll(e){return t(this,void 0,void 0,(function*(){pe.runWithException(e);return(yield this.bridge.send("layouts",Kt.getAll,{type:e})).summaries}))}export(e){return t(this,void 0,void 0,(function*(){pe.runWithException(e);return(yield this.bridge.send("layouts",Kt.export,{type:e})).layouts}))}import(e,n="replace"){return t(this,void 0,void 0,(function*(){if(Oe.runWithException(n),!Array.isArray(e))throw new Error("Import must be called with an array of layouts");if(e.length>1e3)throw new Error("Cannot import more than 1000 layouts at once in Glue42 Core.");const t=e.reduce(((e,t)=>{const n=_e.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=>t.valid.some((t=>t.name===e.name))));yield this.bridge.send("layouts",Kt.import,{layouts:i,mode:n})}))}save(e){return t(this,void 0,void 0,(function*(){Pe.runWithException(e);return(yield this.bridge.send("layouts",Kt.save,{layout:e})).layout}))}restore(e){return t(this,void 0,void 0,(function*(){Te.runWithException(e);const t=e.timeout?2*e.timeout:this.defaultLayoutRestoreTimeoutMS;yield this.bridge.send("layouts",Kt.restore,{layout:e},{methodResponseTimeoutMs:t})}))}remove(e,n){return t(this,void 0,void 0,(function*(){pe.runWithException(e),M.runWithException(n),yield this.bridge.send("layouts",Kt.remove,{type:e,name:n})}))}handleSaveRequest(e){return t(this,void 0,void 0,(function*(){const t={};if(this.saveRequestSubscription)try{const n=this.saveRequestSubscription(e);t.windowContext=null==n?void 0:n.windowContext}catch(e){this.logger.warn(`An error was thrown by the onSaveRequested callback, ignoring the callback: ${JSON.stringify(e)}`)}return t}))}getGlobalPermissionState(){return t(this,void 0,void 0,(function*(){return yield this.bridge.send("layouts",Kt.getGlobalPermissionState,void 0)}))}requestGlobalPermission(){return t(this,void 0,void 0,(function*(){const e=(yield 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)throw new Error("Cannot request permission for multi-window placement from any app other than the Platform.");return{permissionGranted:(yield this.bridge.send("layouts",Kt.requestGlobalPermission,void 0,{methodResponseTimeoutMs:18e4})).isAvailable}}))}checkGlobalActivated(){return t(this,void 0,void 0,(function*(){return{activated:(yield this.bridge.send("layouts",Kt.checkGlobalActivated,void 0)).isAvailable}}))}getDefaultGlobal(){return t(this,void 0,void 0,(function*(){return(yield this.bridge.send("layouts",Kt.getDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})).layout}))}setDefaultGlobal(e){return t(this,void 0,void 0,(function*(){M.runWithException(e),yield this.bridge.send("layouts",Kt.setDefaultGlobal,{name:e},void 0,{includeOperationCheck:!0})}))}clearDefaultGlobal(){return t(this,void 0,void 0,(function*(){yield this.bridge.send("layouts",Kt.clearDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})}))}onAdded(e){return this.export("Global").then((t=>t.forEach((t=>e(t))))).catch((()=>{})),this.export("Workspace").then((t=>t.forEach((t=>e(t))))).catch((()=>{})),this.registry.add(Kt.layoutAdded.name,e)}onChanged(e){return this.registry.add(Kt.layoutChanged.name,e)}onRemoved(e){return this.registry.add(Kt.layoutRemoved.name,e)}subscribeOnSaveRequested(e){if("function"!=typeof e)throw new Error("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function.");if(this.saveRequestSubscription)throw new Error("Cannot subscribe to onSaveRequested, because this client has already subscribed and only one subscription is supported. Consider unsubscribing from the initial one.");return this.saveRequestSubscription=e,()=>{delete this.saveRequestSubscription}}handleOnAdded(e){return t(this,void 0,void 0,(function*(){this.registry.execute(Kt.layoutAdded.name,e)}))}handleOnChanged(e){return t(this,void 0,void 0,(function*(){this.registry.execute(Kt.layoutChanged.name,e)}))}handleOnRemoved(e){return t(this,void 0,void 0,(function*(){this.registry.execute(Kt.layoutRemoved.name,e)}))}}const zt={raiseNotification:{name:"raiseNotification",dataDecoder:ut,resultDecoder:dt},requestPermission:{name:"requestPermission",resultDecoder:ht},notificationShow:{name:"notificationShow",dataDecoder:pt},notificationClick:{name:"notificationClick",dataDecoder:pt},getPermission:{name:"getPermission",resultDecoder:lt},list:{name:"list",resultDecoder:kt},notificationRaised:{name:"notificationRaised",dataDecoder:Tt},notificationClosed:{name:"notificationClosed",dataDecoder:Mt},click:{name:"click"},clear:{name:"clear"},clearAll:{name:"clearAll"}};var Qt={},Xt={get exports(){return Qt},set exports(e){Qt=e}},Yt={},Zt={get exports(){return Yt},set exports(e){Yt=e}},en=1;var tn,nn,on,rn={nextValue:function(){return(en=(9301*en+49297)%233280)/233280},seed:function(e){en=e}},sn="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";function an(){on=!1}function cn(e){if(e){if(e!==tn){if(e.length!==sn.length)throw new Error("Custom alphabet for shortid must be "+sn.length+" unique characters. You submitted "+e.length+" characters: "+e);var t=e.split("").filter((function(e,t,n){return t!==n.lastIndexOf(e)}));if(t.length)throw new Error("Custom alphabet for shortid must be "+sn.length+" unique characters. These characters were not unique: "+t.join(", "));tn=e,an()}}else tn!==sn&&(tn=sn,an())}function un(){return on||(on=function(){tn||cn(sn);for(var e,t=tn.split(""),n=[],i=rn.nextValue();t.length>0;)i=rn.nextValue(),e=Math.floor(i*t.length),n.push(t.splice(e,1)[0]);return n.join("")}())}var dn,hn={get:function(){return tn||sn},characters:function(e){return cn(e),tn},seed:function(e){rn.seed(e),nn!==e&&(an(),nn=e)},lookup:function(e){return un()[e]},shuffled:un},ln="object"==typeof window&&(window.crypto||window.msCrypto);dn=ln&&ln.getRandomValues?function(e){return ln.getRandomValues(new Uint8Array(e))}:function(e){for(var t=[],n=0;n<e;n++)t.push(Math.floor(256*Math.random()));return t};var pn=hn,fn=dn,gn=function(e,t,n){for(var i=(2<<Math.log(t.length-1)/Math.LN2)-1,o=-~(1.6*i*n/t.length),r="";;)for(var s=e(o),a=o;a--;)if((r+=t[s[a]&i]||"").length===+n)return r};var mn,vn,yn=function(e){for(var t,n=0,i="";!t;)i+=gn(fn,pn.get(),1),t=e<Math.pow(16,n+1),n++;return i},bn=yn,wn=1567752802062,In=7;var Cn=function(e){var t="",n=Math.floor(.001*(Date.now()-wn));return n===vn?mn++:(mn=0,vn=n),t+=bn(In),t+=bn(e),mn>0&&(t+=bn(mn)),t+=bn(n)},Sn=hn;var xn=function(e){return!(!e||"string"!=typeof e||e.length<6)&&!new RegExp("[^"+Sn.get().replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&")+"]").test(e)};!function(e){var t=hn,n=Cn,i=xn,o=0;function r(){return n(o)}e.exports=r,e.exports.generate=r,e.exports.seed=function(n){return t.seed(n),e.exports},e.exports.worker=function(t){return o=t,e.exports},e.exports.characters=function(e){return void 0!==e&&t.characters(e),t.shuffled()},e.exports.isValid=i}(Zt),function(e){e.exports=Yt}(Xt);var _n=jt(Qt);class Pn{constructor(){this.registry=Et(),this.notifications={}}handlePlatformShutdown(){this.notifications={},this.registry.clear()}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("notifications.controller.web"),this.logger.trace("starting the web notifications controller"),this.bridge=n.bridge,this.coreGlue=e,this.notificationsSettings=n.config.notifications,this.buildNotificationFunc=n.buildNotification;const t=this.toApi();this.addOperationExecutors(),e.notifications=t,this.logger.trace("notifications are ready")}))}handleBridgeMessage(e){return t(this,void 0,void 0,(function*(){const t=N.runWithException(e.operation),n=zt[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=n.dataDecoder.runWithException(e.data)),yield 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)};return Object.freeze(e)}getPermission(){return t(this,void 0,void 0,(function*(){return(yield this.bridge.send("notifications",zt.getPermission,void 0)).permission}))}requestPermission(){return t(this,void 0,void 0,(function*(){return(yield this.bridge.send("notifications",zt.requestPermission,void 0)).permissionGranted}))}raise(e){return t(this,void 0,void 0,(function*(){const t=at.runWithException(e);t.showToast="boolean"!=typeof t.showToast||t.showToast,t.showInPanel="boolean"!=typeof t.showInPanel||t.showInPanel;if(!(yield this.requestPermission()))throw new Error("Cannot raise the notification, because the user has declined the permission request");const n=Qt.generate(),i=yield this.bridge.send("notifications",zt.raiseNotification,{settings:t,id:n}),o=this.buildNotificationFunc(i.settings,n);return this.notifications[n]=o,o}))}list(){return t(this,void 0,void 0,(function*(){return(yield this.bridge.send("notifications",zt.list,void 0,void 0,{includeOperationCheck:!0})).notifications}))}onRaised(e){if("function"!=typeof e)throw new Error("onRaised expects a callback of type function");return this.registry.add("notification-raised",e)}onClosed(e){if("function"!=typeof e)throw new Error("onRaised expects a callback of type function");return this.registry.add("notification-closed",e)}click(e,n){return t(this,void 0,void 0,(function*(){M.runWithException(e),n&&M.runWithException(n),yield this.bridge.send("notifications",zt.click,{id:e,action:n},void 0,{includeOperationCheck:!0})}))}clear(e){return t(this,void 0,void 0,(function*(){M.runWithException(e),yield this.bridge.send("notifications",zt.clear,{id:e},void 0,{includeOperationCheck:!0})}))}clearAll(){return t(this,void 0,void 0,(function*(){yield this.bridge.send("notifications",zt.clearAll,void 0,void 0,{includeOperationCheck:!0})}))}addOperationExecutors(){zt.notificationShow.execute=this.handleNotificationShow.bind(this),zt.notificationClick.execute=this.handleNotificationClick.bind(this),zt.notificationRaised.execute=this.handleNotificationRaised.bind(this),zt.notificationClosed.execute=this.handleNotificationClosed.bind(this)}handleNotificationShow(e){return t(this,void 0,void 0,(function*(){if(!e.id)return;const t=this.notifications[e.id];t&&t.onshow&&t.onshow()}))}handleNotificationClick(e){var n,i,o,r,s;return t(this,void 0,void 0,(function*(){if(!e.action&&(null===(n=this.notificationsSettings)||void 0===n?void 0:n.defaultClick)&&this.notificationsSettings.defaultClick(this.coreGlue,e.definition),e.action&&(null===(o=null===(i=this.notificationsSettings)||void 0===i?void 0:i.actionClicks)||void 0===o?void 0:o.some((t=>t.action===e.action)))){(null===(s=null===(r=this.notificationsSettings)||void 0===r?void 0:r.actionClicks)||void 0===s?void 0:s.find((t=>t.action===e.action))).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])}))}handleNotificationRaised(e){return t(this,void 0,void 0,(function*(){this.registry.execute("notification-raised",e.notification)}))}handleNotificationClosed(e){return t(this,void 0,void 0,(function*(){this.registry.execute("notification-closed",e)}))}}const Tn={getIntents:{name:"getIntents",resultDecoder:He},findIntent:{name:"findIntent",dataDecoder:ze,resultDecoder:He},raiseIntent:{name:"raiseIntent",dataDecoder:Qe,resultDecoder:et},raise:{name:"raise",dataDecoder:Ze,resultDecoder:et}},kn=2147483647;class Mn{constructor(){this.myIntents=new Set,this.useIntentsResolverUI=!0,this.unregisterIntentPromises=[]}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("intents.controller.web"),this.logger.trace("starting the web intents controller"),this.bridge=n.bridge,this.interop=e.interop,this.legacyIntentsController=n.legacyIntentsHelper,this.checkIfIntentsResolverIsEnabled(n.config);const t=this.toApi();this.logger.trace("no need for platform registration, attaching the intents property to glue and returning"),e.intents=t}))}handlePlatformShutdown(){this.myIntents=new Set,this.unregisterIntentPromises=[]}handleBridgeMessage(e){return t(this,void 0,void 0,(function*(){const t=Fe.runWithException(e.operation),n=Tn[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=n.dataDecoder.runWithException(e.data)),yield 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)}}raise(e){return t(this,void 0,void 0,(function*(){const t=Xe.runWithException(e),n="string"==typeof t?{intent:t}:t;yield Promise.all(this.unregisterIntentPromises);const i=this.buildIntentRequestWithResolverInfo(n),o=yield this.isRaiseOperationSupported();if(!o.supported)return this.logger.warn(`${o.reason}. Invoking legacy raise method`),this.legacyIntentsController.raise(i,this.find.bind(this));this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(e)} and method response timeout of ${this.intentResolverResponseTimeout}ms`);const r=n.waitUserResponseIndefinitely?kn:(n.timeout||this.intentResolverResponseTimeout)+3e4;return yield this.bridge.send("intents",Tn.raise,i,{methodResponseTimeoutMs:r,waitTimeoutMs:r})}))}buildIntentRequestWithResolverInfo(e){return{intentRequest:e,resolverConfig:{enabled:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:e.waitUserResponseIndefinitely?kn:this.intentResolverResponseTimeout}}}isRaiseOperationSupported(){return t(this,void 0,void 0,(function*(){try{const{isSupported:e}=yield this.bridge.send("intents",Nt.operationCheck,{operation:"raise"});return{supported:e,reason:e?"":'The platform of this client is outdated and does not support "raise" operation'}}catch(e){return{supported:!1,reason:'The platform of this client is outdated and does not support "operationCheck" command'}}}))}all(){return t(this,void 0,void 0,(function*(){yield Promise.all(this.unregisterIntentPromises);return(yield this.bridge.send("intents",Tn.getIntents,void 0)).intents}))}addIntentListener(t,n){if(nt.runWithException(t),"function"!=typeof n)throw new Error("Cannot add intent listener, because the provided handler is not a function!");let i;const o="string"==typeof t?t:t.intent,r=this.buildInteropMethodName(o);if(this.myIntents.has(o))throw new Error(`Intent listener for intent ${o} already registered!`);this.myIntents.add(o);const s={unsubscribe:()=>{this.myIntents.delete(o),i.then((()=>this.interop.unregister(r))).catch((e=>this.logger.trace(`Unregistration of a method with name ${r} failed with reason: ${e}`)))}};let a={};if("object"==typeof t){a=e(t,["intent"])}return i=this.interop.register({name:r,flags:{intent:a}},(e=>{if(this.myIntents.has(o))return n(e)})),i.catch((e=>{this.myIntents.delete(o),this.logger.warn(`Registration of a method with name ${r} failed with reason: ${e}`)})),s}register(n,i){return t(this,void 0,void 0,(function*(){if(nt.runWithException(n),"function"!=typeof i)throw new Error("Cannot add intent listener, because the provided handler is not a function!");yield Promise.all(this.unregisterIntentPromises);const t="string"==typeof n?n:n.intent,o=this.buildInteropMethodName(t);if(this.myIntents.has(t))throw new Error(`Intent listener for intent ${t} already registered!`);this.myIntents.add(t);let r={};if("object"==typeof n){r=e(n,["intent"])}try{yield this.interop.register({name:o,flags:{intent:r}},(e=>{if(this.myIntents.has(t))return i(e)}))}catch(e){throw this.myIntents.delete(t),new Error(`Registration of a method with name ${o} failed with reason: ${JSON.stringify(e)}`)}return{unsubscribe:()=>this.unsubscribeIntent(t)}}))}find(e){return t(this,void 0,void 0,(function*(){let t;if(void 0!==e){const n=Ve.runWithException(e);"string"==typeof n?t={filter:{name:n}}:"object"==typeof n&&(t={filter:n})}yield Promise.all(this.unregisterIntentPromises);return(yield this.bridge.send("intents",Tn.findIntent,t)).intents}))}checkIfIntentsResolverIsEnabled(e){var t,n,i,o,r;this.useIntentsResolverUI="boolean"!=typeof(null===(t=e.intents)||void 0===t?void 0:t.enableIntentsResolverUI)||e.intents.enableIntentsResolverUI,this.intentsResolverAppName=null!==(i=null===(n=e.intents)||void 0===n?void 0:n.intentsResolverAppName)&&void 0!==i?i:"intentsResolver",this.intentResolverResponseTimeout=null!==(r=null===(o=e.intents)||void 0===o?void 0:o.methodResponseTimeoutMs)&&void 0!==r?r:6e4}clearUnregistrationPromise(e){this.unregisterIntentPromises=this.unregisterIntentPromises.filter((t=>t!==e))}buildInteropMethodName(e){return`Tick42.FDC3.Intents.${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)}))}}const Rn={name:"platformUnload"},jn={name:"transportSwitchRequest"},An={name:"transportSwitchResponse"},En={name:"getCurrentTransport"},On={name:"getCurrentTransportResponse"},Nn={name:"checkPreferredLogic"},Dn={name:"checkPreferredConnection"},Wn={name:"checkPreferredLogicResponse"},Ln={name:"checkPreferredConnectionResponse"},qn="web-platform",Fn="latest_fdc3_type",Gn={addChannel:{name:"addChannel",dataDecoder:ct}};class Un{constructor(){this.registry=Et(),this.GlueWebChannelsPrefix="___channel___",this.SubsKey="subs",this.ChangedKey="changed",this.replaySubscribe=(e,t)=>{this.get(t).then((t=>{if("object"==typeof t.data&&Object.keys(t.data).length){const n=this.createContextName(t.name);return this.contexts.subscribe(n,((t,n,i,o,r)=>{e(t.data,t,null==r?void 0:r.updaterId)}))}})).then((e=>{e&&"function"==typeof e&&e()})).catch((e=>this.logger.trace(e)))}}handlePlatformShutdown(){this.registry.clear()}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("channels.controller.web"),this.logger.trace("starting the web channels controller"),this.contexts=e.contexts,this.bridge=n.bridge,this.logger.trace("no need for platform registration, attaching the channels property to glue and returning");const t=this.toApi();e.channels=t}))}handleBridgeMessage(){return t(this,void 0,void 0,(function*(){}))}list(){return t(this,void 0,void 0,(function*(){const e=this.getAllChannelNames();return yield Promise.all(e.map((e=>this.get(e))))}))}my(){return this.current()}join(e){return t(this,void 0,void 0,(function*(){const t=this.getAllChannelNames();it(t).runWithException(e),yield this.switchToChannel(e)}))}onChanged(e){return this.changed(e)}leave(){return t(this,void 0,void 0,(function*(){yield this.switchToChannel()}))}toApi(){const e={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),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)};return Object.freeze(e)}createContextName(e){return`${this.GlueWebChannelsPrefix}${e}`}getAllChannelNames(){return this.contexts.all().filter((e=>e.startsWith(this.GlueWebChannelsPrefix))).map((e=>e.replace(this.GlueWebChannelsPrefix,"")))}unsubscribe(){this.unsubscribeFunc&&(this.unsubscribeFunc(),this.unsubscribeFunc=void 0)}switchToChannel(e){return t(this,void 0,void 0,(function*(){if(this.unsubscribe(),this.currentChannelName=e,void 0!==e){const t=this.createContextName(e);this.unsubscribeFunc=yield this.contexts.subscribe(t,((e,t,n,i,o)=>{this.registry.execute(this.SubsKey,e.data,e,null==o?void 0:o.updaterId)}))}this.registry.execute(this.ChangedKey,e)}))}updateData(e,n){return t(this,void 0,void 0,(function*(){const t=this.createContextName(e),i=this.getFDC3Type(n);if(this.contexts.setPathSupported){const e=Object.keys(n).map((e=>({path:`data.${e}`,value:n[e]})));i&&e.push({path:Fn,value:i}),yield this.contexts.setPaths(t,e)}else i&&(n[Fn]=i),yield this.contexts.update(t,{data:n})}))}getFDC3Type(e){const t=Object.keys(e).filter((e=>0===e.indexOf("fdc3_")));if(0!==t.length){if(t.length>1)throw new Error("FDC3 does not support updating of multiple context keys");return t[0].split("_").slice(1).join("_")}}subscribe(e){if("function"!=typeof e)throw new Error("Cannot subscribe to channels, because the provided callback is not a function!");const t=this.current();return t&&this.replaySubscribe(e,t),this.registry.add(this.SubsKey,e)}subscribeFor(e,n){return t(this,void 0,void 0,(function*(){const t=this.getAllChannelNames();if(it(t).runWithException(e),"function"!=typeof n)throw new Error(`Cannot subscribe to channel ${e}, because the provided callback is not a function!`);const i=this.createContextName(e);return this.contexts.subscribe(i,((e,t,i,o,r)=>{n(e.data,e,null==r?void 0:r.updaterId)}))}))}publish(e,t){if("object"!=typeof e)throw new Error("Cannot publish to channel, because the provided data is not an object!");if(void 0!==t){const n=this.getAllChannelNames();return it(n).runWithException(t),this.updateData(t,e)}if(void 0===this.currentChannelName)throw new Error("Cannot publish to channel, because not joined to a channel!");return this.updateData(this.currentChannelName,e)}all(){return t(this,void 0,void 0,(function*(){return this.getAllChannelNames()}))}get(n){return t(this,void 0,void 0,(function*(){const t=this.getAllChannelNames();it(t).runWithException(n);const i=this.createContextName(n),o=yield this.contexts.get(i);if(o.latest_fdc3_type){const t=e(o,["latest_fdc3_type"]);return Object.assign({},t)}return o}))}current(){return this.currentChannelName}changed(e){if("function"!=typeof e)throw new Error("Cannot subscribe to channel changed, because the provided callback is not a function!");return this.registry.add(this.ChangedKey,e)}add(e){return t(this,void 0,void 0,(function*(){const t=ct.runWithException(e);if(this.getAllChannelNames().includes(t.name))throw new Error("There's an already existing channel with such name");return yield this.bridge.send("channels",Gn.addChannel,t),t}))}}const Bn={getEnvironment:{name:"getEnvironment",resultDecoder:X},getBase:{name:"getBase",resultDecoder:X},platformShutdown:{name:"platformShutdown"}};class $n{start(e,n){return t(this,void 0,void 0,(function*(){this.bridge=n.bridge,this.ioc=n,this.addOperationsExecutors(),yield this.setEnvironment()}))}handleBridgeMessage(e){return t(this,void 0,void 0,(function*(){const t=D.runWithException(e.operation),n=Bn[t];if(!n.execute)return;let i=e.data;return n.dataDecoder&&(i=n.dataDecoder.runWithException(e.data)),yield n.execute(i)}))}processPlatformShutdown(){return t(this,void 0,void 0,(function*(){Object.values(this.ioc.controllers).forEach((e=>e.handlePlatformShutdown?e.handlePlatformShutdown():null)),this.ioc.preferredConnectionController.stop(),this.ioc.eventsDispatcher.stop(),yield this.bridge.stop()}))}setEnvironment(){return t(this,void 0,void 0,(function*(){const e=yield this.bridge.send("system",Bn.getEnvironment,void 0),t=yield this.bridge.send("system",Bn.getBase,void 0),n=window.glue42core||window.iobrowser,i=window.glue42core?"glue42core":"iobrowser",o=Object.assign({},n,t,{environment:e});window[i]=Object.freeze(o)}))}addOperationsExecutors(){Bn.platformShutdown.execute=this.processPlatformShutdown.bind(this)}}class Jn{constructor(e,t){this.onclick=()=>{},this.onshow=()=>{},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}}T(S("clientHello"));const Hn={clientHello:{name:"clientHello",resultDecoder:x({widget:x({inject:I()})})}};class Kn{constructor(){this.channels=[],this.unsubFuncs=[],this.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=[]}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("extension.controller.web"),this.windowId=n.publicWindowId,this.logger.trace("starting the extension web controller"),this.bridge=n.bridge,this.channelsController=n.channelsController,this.eventsDispatcher=n.eventsDispatcher;try{yield this.registerWithPlatform()}catch(e){return}this.channels=yield this.channelsController.list();const t=this.eventsDispatcher.onContentMessage(this.handleContentMessage.bind(this)),i=this.channelsController.onChanged((e=>{this.eventsDispatcher.sendContentMessage({command:"channelChange",newChannel:e})}));this.unsubFuncs.push(t),this.unsubFuncs.push(i)}))}handleBridgeMessage(e){return t(this,void 0,void 0,(function*(){}))}handleContentMessage(e){if(!e||"string"!=typeof e.command)return;const t=this.contentCommands[e.command];t&&t.handle(e)}registerWithPlatform(){return t(this,void 0,void 0,(function*(){this.logger.trace("registering with the platform"),this.config=yield this.bridge.send("extension",Hn.clientHello,{windowId:this.windowId}),this.logger.trace("the platform responded to the hello message with a valid extension config")}))}handleWidgetVisualizationPermission(){var e;return t(this,void 0,void 0,(function*(){if(!(null===(e=this.config)||void 0===e?void 0:e.widget.inject))return this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!1});const t=this.channels.find((e=>e.name===this.channelsController.my()));this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!0,channels:this.channels,currentChannel:t})}))}handleChangeChannel(e){return t(this,void 0,void 0,(function*(){"no-channel"!==e.name?yield this.channelsController.join(e.name):yield this.channelsController.leave()}))}}class Vn{constructor(e){this.config=e,this.registry=Et(),this.glue42EventName="Glue42",this.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)}}}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)}wireCustomEventListener(){this._handleMessage=this.handleMessage.bind(this),window.addEventListener(this.glue42EventName,this._handleMessage)}handleMessage(e){var t;const n=e.detail,i=null!==(t=null==n?void 0:n.glue42)&&void 0!==t?t:null==n?void 0:n.glue42core;if(!i)return;const o=i.event,r=this.events[o];r&&r.handle(i.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)}send(e,t,n){const i={};i[t]={event:e,message:n};const o=new CustomEvent(this.glue42EventName,{detail:i});window.dispatchEvent(o)}}class zn{constructor(e){this.coreGlue=e,this.transactionTimeout=15e3,this.transactionLocks={},this.reconnectCounter=0,this.logger=this.coreGlue.logger.subLogger("web.preferred.connection.controller")}stop(){this.webPlatformMessagesUnsubscribe&&this.webPlatformMessagesUnsubscribe()}start(e){return t(this,void 0,void 0,(function*(){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()===qn))throw new Error("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=yield this.getCurrentPlatformTransportState();yield this.checkSwitchTransport(t)}))}handleWebPlatformMessage(e){if("string"==typeof e)return;const t=this.coreGlue.connection.transport.name()===qn,n=e.type,i=e.args,o=e.transactionId;return n===jn.name?this.handleTransportSwitchRequest(i,o):n!==Rn.name||t?n===On.name?this.handleGetCurrentTransportResponse(i,o):n===Nn.name?this.handleCheckPreferredLogic(o):n===Dn.name?this.handleCheckPreferredConnection(i,o):void 0:this.handlePlatformUnload()}reEstablishPlatformPort(){return t(this,void 0,void 0,(function*(){try{yield 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=yield this.getCurrentPlatformTransportState();yield this.checkSwitchTransport(e)}))}checkSwitchTransport(e){return t(this,void 0,void 0,(function*(){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=yield this.coreGlue.connection.switchTransport(e);this.setConnected(),this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(n)}`)}))}getCurrentPlatformTransportState(){return t(this,void 0,void 0,(function*(){this.logger.trace("Requesting the current transport state of the platform.");const e=this.setTransaction(En.name);this.sendPlatformMessage(En.name,e.id);const t=yield e.lock;return this.logger.trace(`The platform responded with transport state: ${JSON.stringify(t)}`),t}))}setTransaction(e){const t={},n=Qt.generate(),i=new Promise(((i,o)=>{let r=!0;t.lift=e=>{r=!1,delete this.transactionLocks[n],i(e)},t.fail=e=>{r=!1,delete this.transactionLocks[n],o(e)},setTimeout((()=>{r&&(r=!1,this.logger.warn(`Transaction for operation: ${e} timed out.`),delete this.transactionLocks[n],o(`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(An.name,t,{success:e.success})})).catch((e=>{this.logger.error(e),this.sendPlatformMessage(An.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];null==i||i.lift(n)}handleCheckPreferredLogic(e){setTimeout((()=>this.sendPlatformMessage(Wn.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(Ln.name,t,e)})).catch((e=>{this.logger.trace(`The connection to ${n} is not possible`),this.sendPlatformMessage(Ln.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()}}class Qn{constructor(e,t,n,i,o){this.bridge=t,this.interop=n,this.appManagerController=i,this.windowsController=o,this.intentsResolverResponsePromises={},this.logger=this.configureLogger(e)}raise(e,n){var i;return t(this,void 0,void 0,(function*(){const{intentRequest:t,resolverConfig:o}=e,r=(yield n(t.intent)).find((e=>e.name===t.intent));if(!r)throw new Error(`Intent with name ${t.intent} not found`);const{open:s,reason:a}=this.checkIfResolverShouldBeOpened(r,t,o);if(!s)return null===(i=this.logger)||void 0===i||i.trace(`Intent Resolver UI won't be used. Reason: ${a}`),this.invokeRaiseIntent(t);return yield this.raiseIntentWithResolverApp(e)}))}configureLogger(e){return e.subLogger("intents.legacy.helper.web")}raiseIntentWithResolverApp(e){return t(this,void 0,void 0,(function*(){const{intentRequest:t,resolverConfig:n}=e;this.logger.trace(`Intents Resolver UI with app name ${n.appName} will be used`);const i=yield this.registerResponseMethod();this.logger.trace(`Registered interop method ${i}`);const o=yield this.openIntentResolverApplication(e,i);this.logger.trace(`Intents Resolver Instance with id ${o.id} opened`);const r=yield this.handleInstanceResponse(o.id),s="app"===r.type?{app:r.applicationName}:{instance:r.instanceId};this.logger.trace(`Intent handler chosen by the user: ${JSON.stringify(s)}`);return yield this.invokeRaiseIntent(Object.assign(Object.assign({},t),{target:s}))}))}handleInstanceResponse(e){var n;return t(this,void 0,void 0,(function*(){try{const{handler:t,intent:i}=yield this.intentsResolverResponsePromises[e].promise;return null===(n=this.logger)||void 0===n||n.trace(`Intent handler chosen for intent ${i}: ${JSON.stringify(t)}`),this.stopResolverInstance(e),t}catch(t){throw this.stopResolverInstance(e),new Error(t)}}))}invokeRaiseIntent(e){return this.bridge.send("intents",Tn.raiseIntent,e)}registerResponseMethod(){return t(this,void 0,void 0,(function*(){const e="T42.Intents.Resolver.Control."+_n();return yield this.interop.register(e,this.resolverResponseHandler.bind(this)),e}))}openIntentResolverApplication(e,n){return t(this,void 0,void 0,(function*(){const{intentRequest:t,resolverConfig:i}=e,o=this.buildStartContext(t,n),r=yield this.buildStartOptions();this.logger.trace(`Starting Intents Resolver UI with context: ${JSON.stringify(o)} and options: ${r}`);const s=yield this.appManagerController.getApplication(i.appName).start(o,r);return this.logger.trace(`Intents Resolver instance with id ${s.id} opened`),this.subscribeOnInstanceStopped(s),this.createResponsePromise(t.intent,s.id,n,i.waitResponseTimeout),s}))}cleanUpIntentResolverPromise(e){return t(this,void 0,void 0,(function*(){const t=this.intentsResolverResponsePromises[e];if(!t)return;this.interop.unregister(t.methodName).catch((e=>this.logger.warn(e))),delete this.intentsResolverResponsePromises[e]}))}buildStartContext(e,t){return{intent:e,callerId:this.interop.instance.instance,methodName:t}}buildStartOptions(){return t(this,void 0,void 0,(function*(){const e=yield this.getTargetBounds();return{top:(e.height-440)/2+e.top,left:(e.width-400)/2+e.left,width:400,height:440}}))}getTargetBounds(){return t(this,void 0,void 0,(function*(){const e=(yield this.tryGetWindowBasedBounds())||(yield this.tryGetWorkspaceBasedBounds());if(e)return this.logger.trace(`Opening Intents Resolver UI with bounds: ${JSON.stringify(e)}`),e;const t={top:window.screen.availTop||0,left:window.screen.availLeft||0,width:window.screen.width,height:window.screen.height};return this.logger.trace(`Opening Intents Resolver UI relative to my screen bounds: ${JSON.stringify(t)}`),t}))}tryGetWindowBasedBounds(){return t(this,void 0,void 0,(function*(){try{const e=yield this.windowsController.my().getBounds();return this.logger.trace(`Opening the resolver UI relative to my window bounds: ${JSON.stringify(e)}`),e}catch(e){this.logger.trace(`Failure to get my window bounds: ${JSON.stringify(e)}`)}}))}tryGetWorkspaceBasedBounds(){return t(this,void 0,void 0,(function*(){try{yield this.bridge.send("workspaces",Nt.operationCheck,{operation:"getWorkspaceWindowFrameBounds"});const e=(yield this.bridge.send("workspaces",Nt.getWorkspaceWindowFrameBounds,{itemId:this.windowsController.my().id})).bounds;return this.logger.trace(`Opening the resolver UI relative to my workspace frame window bounds: ${JSON.stringify(e)}`),e}catch(e){this.logger.trace(`Failure to get my workspace frame window bounds: ${JSON.stringify(e)}`)}}))}subscribeOnInstanceStopped(e){const{application:t}=e,n=t.onInstanceStopped((i=>{if(i.id!==e.id)return;const o=this.intentsResolverResponsePromises[i.id];if(!o)return n();o.reject(`Cannot resolve raised intent "${o.intent}" - User closed ${t.name} app without choosing an intent handler`),this.cleanUpIntentResolverPromise(i.id),n()}))}createResponsePromise(e,t,n,i){let o=()=>{},r=()=>{};const s=Dt(((e,t)=>{o=e,r=t}),i,`Timeout of ${i}ms hit waiting for the user to choose a handler for intent ${e}`);this.intentsResolverResponsePromises[t]={intent:e,resolve:o,reject:r,promise:s,methodName:n}}resolverResponseHandler(e,t){const n=Ue.run(e),i=t.instance;if(n.ok)return this.logger.trace(`Intent Resolver instance with id ${i} send a valid response: ${JSON.stringify(n.result)}`),this.intentsResolverResponsePromises[i].resolve(n.result);this.logger.trace(`Intent Resolver instance with id ${i} sent an invalid response. Error: ${JSON.stringify(n.error)}`),this.intentsResolverResponsePromises[i].reject(n.error.message),this.stopResolverInstance(i)}stopResolverInstance(e){const t=this.appManagerController.getInstances().find((t=>t.id===e));t&&t.stop().catch((e=>this.logger.error(e)))}checkIfIntentHasMoreThanOneHandler(e,t){return"object"!=typeof t.target&&(t.handlers?t.handlers.length>1:e.handlers.length>1)}checkIfResolverShouldBeOpened(e,t,n){if(!n.enabled)return{open:!1,reason:"Intent Resolver is disabled. Raising intent to first found handler"};if(!this.appManagerController.getApplication(n.appName))return{open:!1,reason:`Application with name ${n.appName} not found`};return this.checkIfIntentHasMoreThanOneHandler(e,t)?{open:!0}:{open:!1,reason:"Raised intent has only one handler"}}}const Xn={getCurrent:{name:"getCurrent",resultDecoder:St},list:{name:"list",resultDecoder:xt},select:{name:"select",dataDecoder:_t}};class Yn{constructor(){this.registry=Et(),this.activeThemeSubs=0}start(e,n){return t(this,void 0,void 0,(function*(){this.logger=e.logger.subLogger("themes.controller.web"),this.logger.trace("starting the web themes controller"),this.bridge=n.bridge;const t=this.toApi();e.themes=t,this.logger.trace("themes are ready")}))}handlePlatformShutdown(){var e;this.registry.clear(),this.activeThemeSubs=0,null===(e=this.themesSubscription)||void 0===e||e.close(),delete this.themesSubscription}handleBridgeMessage(){return t(this,void 0,void 0,(function*(){}))}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)}getCurrent(){return t(this,void 0,void 0,(function*(){return(yield this.bridge.send("themes",Xn.getCurrent,void 0,void 0,{includeOperationCheck:!0})).theme}))}list(){return t(this,void 0,void 0,(function*(){return(yield this.bridge.send("themes",Xn.list,void 0,void 0,{includeOperationCheck:!0})).themes}))}select(e){return t(this,void 0,void 0,(function*(){M.runWithException(e),yield this.bridge.send("themes",Xn.select,{name:e},void 0,{includeOperationCheck:!0})}))}onChanged(e){return t(this,void 0,void 0,(function*(){if("function"!=typeof e)throw new Error("onChanged requires a callback of type function");const t=this.themesSubscription?Promise.resolve():this.configureThemeSubscription();yield t,++this.activeThemeSubs;const n=this.registry.add("on-theme-change",e);return()=>this.themeUnsub(n)}))}configureThemeSubscription(){return t(this,void 0,void 0,(function*(){this.themesSubscription||(this.themesSubscription=yield this.bridge.createNotificationsSteam(),this.themesSubscription.onData((e=>{const t=e.data,n=St.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)})),this.themesSubscription.onClosed((()=>{this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"),this.registry.clear(),this.activeThemeSubs=0,delete this.themesSubscription})))}))}themeUnsub(e){var t;e(),--this.activeThemeSubs,this.activeThemeSubs||(null===(t=this.themesSubscription)||void 0===t||t.close(),delete this.themesSubscription)}}class Zn{constructor(){this.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}}get communicationId(){return this._communicationId}get publicWindowId(){return this._publicWindowId}get windowsController(){return this._windowsControllerInstance||(this._windowsControllerInstance=new Wt),this._windowsControllerInstance}get appManagerController(){return this._appManagerControllerInstance||(this._appManagerControllerInstance=new $t),this._appManagerControllerInstance}get layoutsController(){return this._layoutsControllerInstance||(this._layoutsControllerInstance=new Vt),this._layoutsControllerInstance}get themesController(){return this._themesControllerInstance||(this._themesControllerInstance=new Yn),this._themesControllerInstance}get notificationsController(){return this._notificationsControllerInstance||(this._notificationsControllerInstance=new Pn),this._notificationsControllerInstance}get intentsController(){return this._intentsControllerInstance||(this._intentsControllerInstance=new Mn),this._intentsControllerInstance}get legacyIntentsHelper(){return this._legacyIntentsHelperInstance||(this._legacyIntentsHelperInstance=new Qn(this._coreGlue.logger,this.bridge,this._coreGlue.interop,this.appManagerController,this.windowsController)),this._legacyIntentsHelperInstance}get systemController(){return this._systemControllerInstance||(this._systemControllerInstance=new $n),this._systemControllerInstance}get channelsController(){return this._channelsControllerInstance||(this._channelsControllerInstance=new Un),this._channelsControllerInstance}get extensionController(){return this._extensionController||(this._extensionController=new Kn),this._extensionController}get eventsDispatcher(){return this._eventsDispatcher||(this._eventsDispatcher=new Vn(this.config)),this._eventsDispatcher}get bridge(){return this._bridgeInstance||(this._bridgeInstance=new Ut(this._coreGlue,this.communicationId)),this._bridgeInstance}get preferredConnectionController(){return this._preferredConnectionController||(this._preferredConnectionController=new zn(this._coreGlue)),this._preferredConnectionController}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}buildWebWindow(e,n){return t(this,void 0,void 0,(function*(){const t=new Ot(e,n,this.bridge),i=yield t.toApi();return{id:e,model:t,api:i}}))}buildNotification(e,t){return new Jn(e,t)}buildApplication(e,n){return t(this,void 0,void 0,(function*(){const t=new Ht(e,[],this.appManagerController).toApi(),i=n.map((e=>this.buildInstance(e,t)));return t.instances.push(...i),t}))}buildInstance(e,t){return new Jt(e,this.bridge,t).toApi()}}var ei="3.0.5";var ti=function(e,t){return ti=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},ti(e,t)};function ni(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}ti(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var ii=function(){return ii=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},ii.apply(this,arguments)};function oi(e,t,n,i){return new(n||(n=Promise))((function(o,r){function s(e){try{c(i.next(e))}catch(e){r(e)}}function a(e){try{c(i.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))}function ri(e,t){var n,i,o,r,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;r&&(r=0,a[0]&&(s=0)),s;)try{if(n=1,i&&(o=2&a[0]?i.return:a[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,a[1])).done)return o;switch(i=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,i=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],i=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function si(e,t,n){if(n||2===arguments.length)for(var i,o=0,r=t.length;o<r;o++)!i&&o in t||(i||(i=Array.prototype.slice.call(t,0,o)),i[o]=t[o]);return e.concat(i||Array.prototype.slice.call(t))}var ai={STRING:1,NUMBER:2,TIMESTAMP:3,OBJECT:4};function ci(e){return e.type===ai.TIMESTAMP?"timestamp":e.type===ai.NUMBER?"number":e.type===ai.STRING?"string":e.type===ai.OBJECT?"object":"unknown"}function ui(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function di(e){var t={},n=ci(e);if("object"===n){var i=Object.keys(e.value).reduce((function(t,n){var i=ui(e.value[n]);if("object"===i){var o=hi(e.value[n]);t[n]={type:"object",description:"",context:{},composite:o}}else t[n]={type:i,description:"",context:{}};return t}),{});t.composite=i}return t.name=li(e.path.join("/")+"/"+e.name),t.type=n,t.description=e.description,t.context={},t}function hi(e){return Object.keys(e).reduce((function(t,n){var i=ui(e[n]);return t[n]="object"===i?{type:"object",description:"",context:{},composite:hi(e[n])}:{type:i,description:"",context:{}},t}),{})}function li(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function pi(e){return"timestamp"===ci(e)?Date.now():fi(e.value)}function fi(e){return"object"!=typeof e?e:Object.keys(e).reduce((function(t,n){var i=e[n];return"object"==typeof i&&i.constructor!==Date?t[n]=fi(i):i.constructor===Date?t[n]=new Date(i).getTime():i.constructor===Boolean?t[n]=i.toString():t[n]=i,t}),{})}function gi(e){return e.reduce((function(e,t){return e.concat(Array.isArray(t)?gi(t):t)}),[])}function mi(e){var t=gi(e.root.getAggregateState()),n=t.sort((function(e,t){return e.state?t.state?t.state-e.state:-1:1}))[0],i=function(e){var t="";return e.forEach((function(e,n,i){var o=e.path.join(".");n===i.length-1?t+=o+"."+e.name+": "+e.description:t+=o+"."+e.name+": "+e.description+","})),t.length>100?t.slice(0,100)+"...":t}(t);return{description:i,value:n.state}}var vi={validate:function(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")}},yi=function(){function e(e,t,n,i,o){this.definition=e,this.system=t,this.transport=n,this.value=i,this.type=o,this.path=[],vi.validate(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)}return Object.defineProperty(e.prototype,"repo",{get:function(){var e;return null===(e=this.system)||void 0===e?void 0:e.repo},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"id",{get:function(){return"".concat(this.system.path,"/").concat(name)},enumerable:!1,configurable:!0}),e.prototype.update=function(e){return this.value=e,this.transport.updateMetric(this)},e}(),bi=function(e){function t(t,n,i,o){return e.call(this,t,n,i,o,ai.NUMBER)||this}return ni(t,e),t.prototype.incrementBy=function(e){this.update(this.value+e)},t.prototype.increment=function(){this.incrementBy(1)},t.prototype.decrement=function(){this.incrementBy(-1)},t.prototype.decrementBy=function(e){this.incrementBy(-1*e)},t}(yi),wi=function(e){function t(t,n,i,o){return e.call(this,t,n,i,o,ai.OBJECT)||this}return ni(t,e),t.prototype.update=function(e){return this.mergeValues(e),this.transport.updateMetric(this)},t.prototype.mergeValues=function(e){var t=this;return Object.keys(this.value).forEach((function(n){void 0!==e[n]&&(t.value[n]=e[n])}))},t}(yi),Ii=function(e){function t(t,n,i,o){return e.call(this,t,n,i,o,ai.STRING)||this}return ni(t,e),t}(yi),Ci=function(e){function t(t,n,i,o){return e.call(this,t,n,i,o,ai.TIMESTAMP)||this}return ni(t,e),t.prototype.now=function(){this.update(new Date)},t}(yi);function Si(e,t,n,i,o){if(!t)throw new Error("Repository is required");if(!n)throw new Error("Transport is required");var r,s,a=n,c=e,u=o||"",d=t,h=i,l=function e(t){if(!t||!t.parent)return[];var n=e(t.parent);return n.push(t.name),n}(i),p={},f=(s="/",((r=l)&&r.length>0?r.join(s):"")+e),g=t.root,m=[],v=[];function y(e,t,n,i){var o={name:""};o="string"==typeof e?{name:e}:e;var r=v.filter((function(e){return e.name===o.name}));if(r.length>0){var s=r[0];if(s.type!==t)throw new Error("A metric named ".concat(o.name," is already defined with different type."));return void 0!==n&&s.update(n).catch((function(){})),s}var a=i(o);return v.push(a),a}var b={get name(){return c},get description(){return u},get repo(){return d},get parent(){return h},path:l,id:f,root:g,get subSystems(){return m},get metrics(){return v},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");var n=m.filter((function(t){return t.name===e}));if(n.length>0)return n[0];var i=Si(e,d,a,b,t);return m.push(i),i},getState:function(){return p},setState:function(e,t){p={state:e,description:t},a.updateSystem(b,p)},stringMetric:function(e,t){return y(e,ai.STRING,t,(function(e){return new Ii(e,b,a,t)}))},timestampMetric:function(e,t){return y(e,ai.TIMESTAMP,t,(function(e){return new Ci(e,b,a,t)}))},objectMetric:function(e,t){return y(e,ai.OBJECT,t,(function(e){return new wi(e,b,a,t)}))},numberMetric:function(e,t){return y(e,ai.NUMBER,t,(function(e){return new bi(e,b,a,t)}))},getAggregateState:function(){var e=[];return Object.keys(p).length>0&&e.push({name:c,path:l,state:p.state,description:p.description}),m.forEach((function(t){var n=t.getAggregateState();n.length>0&&e.push.apply(e,n)})),e}};return a.createSystem(b),b}var xi=function(){function e(e,t){t.init(this),this.root=Si("",this,t),this.addSystemMetrics(this.root,e.clickStream||void 0===e.clickStream)}return e.prototype.addSystemMetrics=function(e,t){if("undefined"!=typeof navigator&&e.stringMetric("UserAgent",navigator.userAgent),t&&"undefined"!=typeof document){var n=e.subSystem("ClickStream"),i=function(e){var t;if(e.target){var i=e.target,o=i&&null!==(t=i.getAttribute("class"))&&void 0!==t?t:"";n.objectMetric("LastBrowserEvent",{type:"click",timestamp:new Date,target:{className:o,id:i.id,type:"<"+i.tagName.toLowerCase()+">",href:i.href||""}})}};n.objectMetric("Page",{title:document.title,page:window.location.href}),document.addEventListener?document.addEventListener("click",i):document.attachEvent("onclick",i)}e.stringMetric("StartTime",(new Date).toString());var o=e.stringMetric("StartURL",""),r=e.stringMetric("AppName","");if("undefined"!=typeof window){if(void 0!==window.location){var s=window.location.href;o.update(s)}void 0!==window.glue42gd&&r.update(window.glue42gd.appName)}},e}(),_i=function(){function e(){}return e.prototype.init=function(e){},e.prototype.createSystem=function(e){return Promise.resolve()},e.prototype.updateSystem=function(e,t){return Promise.resolve()},e.prototype.createMetric=function(e){return Promise.resolve()},e.prototype.updateMetric=function(e){return Promise.resolve()},e}(),Pi=function(){function e(e,t,n){this.api=e,this.lastCount=0,this.initialPublishTimeout=1e4,this.publishInterval=6e4,this.initialPublishTimeout=null!=t?t:this.initialPublishTimeout,this.publishInterval=null!=n?n:this.publishInterval,this.scheduleCollection(),this.system=this.api.subSystem("performance","Performance data published by the web application")}return e.prototype.scheduleCollection=function(){var e=this;setTimeout((function(){e.collect(),setInterval((function(){e.collect()}),e.publishInterval)}),this.initialPublishTimeout)},e.prototype.collect=function(){try{this.collectMemory(),this.collectEntries()}catch(e){}},e.prototype.collectMemory=function(){var e=window.performance.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}))},e.prototype.collectEntries=function(){var e=window.performance.getEntries();if(!(e.length<=this.lastCount)){this.lastCount=e.length;var t=e.map((function(e){return e.toJSON()}));this.system.stringMetric("entries",JSON.stringify(t))}},e}(),Ti=function(e){var t;t=e.connection&&"object"==typeof e.connection?function(e,t){var n,i,o=this;if(!e||"object"!=typeof e)throw new Error("Connection is required parameter");var r=function(e){s(e.root)},s=function(e){a(e),e.metrics.forEach((function(e){c(e)})),e.subSystems.forEach((function(e){s(e)}))},a=function(e){return oi(o,void 0,void 0,(function(){var t,o;return ri(this,(function(r){switch(r.label){case 0:return void 0===e.parent?[2]:[4,n];case 1:return r.sent(),t={name:li(e.path.join("/")+"/"+e.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}},o={type:"define",metrics:[t]},i.send(o),[2]}}))}))},c=function(e){return oi(o,void 0,void 0,(function(){var t,o,r;return ri(this,(function(s){switch(s.label){case 0:return t=d(e),[4,n];case 1:return s.sent(),o=di(t),r={type:"define",metrics:[o]},i.send(r),void 0!==t.value&&u(t),[2]}}))}))},u=function(e){if(h()){var t=pi(e),n={type:"publish",values:[{name:li(e.path.join("/")+"/"+e.name),value:t,timestamp:Date.now()}]};return i.sendFireAndForget(n)}return Promise.resolve()},d=function(e){var t=ii({},e);return"object"==typeof e.value&&null!==e.value&&(t.value=ii({},e.value)),t},h=function(){var e;try{return(null!==(e=t.canUpdateMetric)&&void 0!==e?e:function(){return!0})()}catch(e){return!0}};return{init:function(o){var s;n=new Promise((function(e){s=e})),(i=e.domain("metrics")).onJoined((function(e){!e&&s&&(s(),s=void 0);var t={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};i.send(t),e&&r(o)})),i.join({system:t.system,service:t.service,instance:t.instance})},createSystem:a,updateSystem:function(t,r){return oi(o,void 0,void 0,(function(){var o,s,a;return ri(this,(function(c){switch(c.label){case 0:return[4,n];case 1:return c.sent(),o={type:"publish",values:[{name:li(t.path.join("/")+"/"+t.name+"/State"),value:{Description:r.description,Value:r.state},timestamp:Date.now()}]},i.send(o),s=mi(t),a={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:s.description,Value:s.value},timestamp:Date.now()}]},i.send(a),[2]}}))}))},createMetric:c,updateMetric:function(e){return oi(o,void 0,void 0,(function(){var t;return ri(this,(function(i){switch(i.label){case 0:return t=d(e),[4,n];case 1:return i.sent(),u(t),[2]}}))}))}}}(e.connection,e):new _i;var n=new xi(e,t).root;e.disableAutoAppSystem||(n=n.subSystem("App"));var i=function(e){var t,n=e.subSystem("reporting"),i={name:"features"},o=function(e,o,r){if(void 0===e||""===e)throw new Error("name is mandatory");if(void 0===o||""===o)throw new Error("action is mandatory");if(void 0===r||""===r)throw new Error("payload is mandatory");t?t.update({name:e,action:o,payload:r}):t=n.objectMetric(i,{name:e,action:o,payload:r})};return e.featureMetric=o,e}(n);return function(e,t){var n,i;if("undefined"==typeof window)return;var o=null===(i=null===(n=null===window||void 0===window?void 0:window.glue42gd)||void 0===n?void 0:n.metrics)||void 0===i?void 0:i.pagePerformanceMetrics;o&&(t=o);(null==t?void 0:t.enabled)&&new Pi(e,t.initialPublishTimeout,t.publishInterval)}(i,e.pagePerformanceMetrics),i};var ki="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Mi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Ri(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 o=n instanceof Error?n:new Error(n);if(t)t(o);else{var r='[ERROR] callback-registry: User callback for key "'+i+'" failed: '+o.stack;if(e)switch(e.errorHandling){case"log":return console.error(r);case"silent":return;case"throw":throw new Error(r)}console.error(r)}}return{add:function(e,t,o){var r=n[e];return r||(r=[],n[e]=r),r.push(t),o&&setTimeout((function(){o.forEach((function(o){var r;if(null===(r=n[e])||void 0===r?void 0:r.includes(t))try{Array.isArray(o)?t.apply(void 0,o):t.apply(void 0,[o])}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=[],o=1;o<arguments.length;o++)t[o-1]=arguments[o];var r=n[e];if(!r||0===r.length)return[];var s=[];return r.forEach((function(n){try{var o=n.apply(void 0,t);s.push(o)}catch(t){s.push(void 0),i(t,e)}})),s},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}Ri.default=Ri;var ji=Ri,Ai=function(){function e(e,t){var n=this;this.registry=ji(),this.gw=e.facade,this.gw.connect((function(e,t){n.messageHandler(t)})).then((function(e){n.client=e}))}return Object.defineProperty(e.prototype,"isObjectBasedTransport",{get:function(){return!0},enumerable:!1,configurable:!0}),e.prototype.sendObject=function(e){return this.client?(this.client.send(e),Promise.resolve(void 0)):Promise.reject("not connected")},e.prototype.send=function(e){return Promise.reject("not supported")},e.prototype.onMessage=function(e){return this.registry.add("onMessage",e)},e.prototype.onConnectedChanged=function(e){return e(!0),function(){}},e.prototype.close=function(){return Promise.resolve()},e.prototype.open=function(){return Promise.resolve()},e.prototype.name=function(){return"in-memory"},e.prototype.reconnect=function(){return Promise.resolve()},e.prototype.messageHandler=function(e){this.registry.execute("onMessage",e)},e}(),Ei=function(){function e(e,t){var n=this;this.logger=t,this.registry=ji(),this.worker=new SharedWorker(e),this.worker.port.onmessage=function(e){n.messageHandler(e.data)}}return Object.defineProperty(e.prototype,"isObjectBasedTransport",{get:function(){return!0},enumerable:!1,configurable:!0}),e.prototype.sendObject=function(e){return this.worker.port.postMessage(e),Promise.resolve()},e.prototype.send=function(e){return Promise.reject("not supported")},e.prototype.onMessage=function(e){return this.registry.add("onMessage",e)},e.prototype.onConnectedChanged=function(e){return e(!0),function(){}},e.prototype.close=function(){return Promise.resolve()},e.prototype.open=function(){return Promise.resolve()},e.prototype.name=function(){return"shared-worker"},e.prototype.reconnect=function(){return Promise.resolve()},e.prototype.messageHandler=function(e){this.registry.execute("onMessage",e)},e}(),Oi=function(){function e(){}return e.isNode=function(){if(void 0!==e._isNode)return e._isNode;if("undefined"!=typeof window)return e._isNode=!1,!1;try{e._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(t){e._isNode=!1}return e._isNode},e}(),Ni=function(){function e(){var e=this;this.rejected=!1,this.resolved=!1,this.promise=new Promise((function(t,n){e.resolve=function(n){e.resolved=!0,t(n)},e.reject=function(t){e.rejected=!0,n(t)}}))}return e.delay=function(e){return new Promise((function(t){return setTimeout(t,e)}))},Object.defineProperty(e.prototype,"ended",{get:function(){return this.rejected||this.resolved},enumerable:!1,configurable:!0}),e}(),Di={};function Wi(e){var t=Di[e];if(t)return t;var n=[];function i(){return(new Date).getTime()}var o,r,s=i();function a(e,t){var o=null!=t?t:i(),r=0;n.length>0&&(r=o-n[n.length-1].time),n.push({name:e,time:o,diff:r})}a("start",s);var c={get startTime(){return s},get endTime(){return o},get period(){return r},stop:function(){return a("end",o=i()),r=o-s},mark:a,marks:n};return Di[e]=c,c}var Li=Oi.isNode()?require("ws"):window.WebSocket,qi=function(){function e(e,t){if(this.startupTimer=Wi("connection"),this._running=!0,this._registry=ji(),this.wsRequests=[],this.settings=e,this.logger=t,!this.settings.ws)throw new Error("ws is missing")}return e.prototype.onMessage=function(e){return this._registry.add("onMessage",e)},e.prototype.send=function(e,t){var n=this;return new Promise((function(t,i){n.waitForSocketConnection((function(){var o;try{null===(o=n.ws)||void 0===o||o.send(e),t()}catch(e){i(e)}}),i)}))},e.prototype.open=function(){var e=this;return this.logger.info("opening ws..."),this._running=!0,new Promise((function(t,n){e.waitForSocketConnection(t,n)}))},e.prototype.close=function(){return this._running=!1,this.ws&&this.ws.close(),Promise.resolve()},e.prototype.onConnectedChanged=function(e){return this._registry.add("onConnectedChanged",e)},e.prototype.name=function(){return this.settings.ws},e.prototype.reconnect=function(){var e;null===(e=this.ws)||void 0===e||e.close();var t=new Ni;return this.waitForSocketConnection((function(){t.resolve()})),t.promise},e.prototype.waitForSocketConnection=function(e,t){var n;t=null!=t?t:function(){},this._running?1!==(null===(n=this.ws)||void 0===n?void 0:n.readyState)?(this.wsRequests.push({callback:e,failed:t}),this.wsRequests.length>1||this.openSocket()):e():t("wait for socket on ".concat(this.settings.ws," failed - socket closed by user"))},e.prototype.openSocket=function(e,t){return oi(this,void 0,void 0,(function(){var n=this;return ri(this,(function(i){switch(i.label){case 0:if(this.startupTimer.mark("opening-socket"),void 0===e&&(e=this.settings.reconnectInterval),void 0===t&&(t=this.settings.reconnectAttempts),void 0!==t){if(0===t)return this.notifyForSocketState("wait for socket on ".concat(this.settings.ws," failed - no more retries left")),[2];this.logger.debug("will retry ".concat(t," more times (every ").concat(e," ms)"))}i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.initiateSocket()];case 2:return i.sent(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState(),[3,4];case 3:return i.sent(),setTimeout((function(){var i=void 0===t?void 0:t-1;n.openSocket(e,i)}),e),[3,4];case 4:return[2]}}))}))},e.prototype.initiateSocket=function(){var e=this,t=new Ni;return this.logger.debug("initiating ws to ".concat(this.settings.ws,"...")),this.ws=new Li(this.settings.ws||""),this.ws.onerror=function(n){var i="";try{i=JSON.stringify(n)}catch(e){var o=new WeakSet;i=JSON.stringify(n,(function(e,t){if("object"==typeof t&&null!==t){if(o.has(t))return;o.add(t)}return t}))}t.reject("error"),e.notifyStatusChanged(!1,i)},this.ws.onclose=function(n){e.logger.info("ws closed ".concat(n)),t.reject("closed"),e.notifyStatusChanged(!1)},this.ws.onopen=function(){var n;e.startupTimer.mark("ws-opened"),e.logger.info("ws opened ".concat(null===(n=e.settings.identity)||void 0===n?void 0:n.application)),t.resolve(),e.notifyStatusChanged(!0)},this.ws.onmessage=function(t){e._registry.execute("onMessage",t.data)},t.promise},e.prototype.notifyForSocketState=function(e){this.wsRequests.forEach((function(t){e?t.failed&&t.failed(e):t.callback()})),this.wsRequests=[]},e.prototype.notifyStatusChanged=function(e,t){this._registry.execute("onConnectedChanged",e,t)},e}(),Fi={},Gi={get exports(){return Fi},set exports(e){Fi=e}},Ui={},Bi={get exports(){return Ui},set exports(e){Ui=e}},$i=1;var Ji,Hi,Ki,Vi={nextValue:function(){return($i=(9301*$i+49297)%233280)/233280},seed:function(e){$i=e}},zi="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";function Qi(){Ki=!1}function Xi(e){if(e){if(e!==Ji){if(e.length!==zi.length)throw new Error("Custom alphabet for shortid must be "+zi.length+" unique characters. You submitted "+e.length+" characters: "+e);var t=e.split("").filter((function(e,t,n){return t!==n.lastIndexOf(e)}));if(t.length)throw new Error("Custom alphabet for shortid must be "+zi.length+" unique characters. These characters were not unique: "+t.join(", "));Ji=e,Qi()}}else Ji!==zi&&(Ji=zi,Qi())}function Yi(){return Ki||(Ki=function(){Ji||Xi(zi);for(var e,t=Ji.split(""),n=[],i=Vi.nextValue();t.length>0;)i=Vi.nextValue(),e=Math.floor(i*t.length),n.push(t.splice(e,1)[0]);return n.join("")}())}var Zi,eo={get:function(){return Ji||zi},characters:function(e){return Xi(e),Ji},seed:function(e){Vi.seed(e),Hi!==e&&(Qi(),Hi=e)},lookup:function(e){return Yi()[e]},shuffled:Yi},to="object"==typeof window&&(window.crypto||window.msCrypto);Zi=to&&to.getRandomValues?function(e){return to.getRandomValues(new Uint8Array(e))}:function(e){for(var t=[],n=0;n<e;n++)t.push(Math.floor(256*Math.random()));return t};var no=eo,io=Zi,oo=function(e,t,n){for(var i=(2<<Math.log(t.length-1)/Math.LN2)-1,o=-~(1.6*i*n/t.length),r="";;)for(var s=e(o),a=o;a--;)if((r+=t[s[a]&i]||"").length===+n)return r};var ro,so,ao=function(e){for(var t,n=0,i="";!t;)i+=oo(io,no.get(),1),t=e<Math.pow(16,n+1),n++;return i},co=ao,uo=1567752802062,ho=7;var lo=function(e){var t="",n=Math.floor(.001*(Date.now()-uo));return n===so?ro++:(ro=0,so=n),t+=co(ho),t+=co(e),ro>0&&(t+=co(ro)),t+=co(n)},po=eo;var fo=function(e){return!(!e||"string"!=typeof e||e.length<6)&&!new RegExp("[^"+po.get().replace(/[|\\{}()[\]^$+*?.-]/g,"\\$&")+"]").test(e)};!function(e){var t=eo,n=lo,i=fo,o=0;function r(){return n(o)}e.exports=r,e.exports.generate=r,e.exports.seed=function(n){return t.seed(n),e.exports},e.exports.worker=function(t){return o=t,e.exports},e.exports.characters=function(e){return void 0!==e&&t.characters(e),t.shuffled()},e.exports.isValid=i}(Bi),function(e){e.exports=Ui}(Gi);var go=Mi(Fi);function mo(e,t,n,i,o){null==e&&(e="global"),i=i||["success"],o=o||["error"];var r,s=!1,a=!1,c=!1,u=ji();t.disconnected((function(){c=!1,n.debug("connection is down"),s=!1,a=!0,u.execute("onLeft",{disconnected:!0})})),t.loggedIn((function(){c=!0,a&&(n.debug("connection is now up - trying to reconnect..."),h(r))})),t.on("success",(function(e){return p(e)})),t.on("error",(function(e){return l(e)})),t.on("result",(function(e){return p(e)})),i&&i.forEach((function(e){t.on(e,(function(e){return p(e)}))})),o&&o.forEach((function(e){t.on(e,(function(e){return l(e)}))}));var d={};function h(t){return r=t,new Promise((function(i,o){if(s)i({});else{var r;if("global"===e)r=c?Promise.resolve({}):Promise.reject("not connected to gateway");else n.debug("joining domain ".concat(e)),r=g({type:"join",destination:e,domain:"global",options:t});r.then((function(){!function(){n.debug("did join "+e),s=!0;var t=a;a=!1,u.execute("onJoined",t)}(),i({})})).catch((function(t){n.debug("error joining "+e+" domain: "+JSON.stringify(t)),o(t)}))}}))}function l(t){if(e===t.domain){var n=t.request_id;if(n){var i=d[n];i&&i.error(t)}}}function p(t){if(t.domain===e){var n=t.request_id;if(n){var i=d[n];i&&i.success(t)}}}function f(){return go()}function g(i,o,r){r=r||{},i.request_id=i.request_id||f(),i.domain=i.domain||e,r.skipPeerId||(i.peer_id=t.peerId);var s=i.request_id;return new Promise((function(e,a){d[s]={success:function(t){delete d[s],t._tag=o,e(t)},error:function(e){n.warn("GW error - ".concat(JSON.stringify(e)," for request ").concat(JSON.stringify(i))),delete d[s],e._tag=o,a(e)}},t.send(i,r).catch((function(e){d[s].error({err:e})}))}))}return{join:h,leave:function(){return"global"===e?Promise.resolve():(n.debug("stopping session "+e+"..."),a=!1,g({type:"leave",destination:e,domain:"global"}).then((function(){s=!1,u.execute("onLeft")})).catch((function(){s=!1,u.execute("onLeft")})))},onJoined:function(e){return s&&e(!1),u.add("onJoined",e)},onLeft:function(e){return s||e(),u.add("onLeft",e)},send:g,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:function(i,o){t.on(i,(function(t){if(t.domain===e)try{o(t)}catch(e){n.error("Callback failed: ".concat(e," \n ").concat(e.stack," \n msg was: ").concat(JSON.stringify(t)),e)}}))},loggedIn:function(e){return t.loggedIn(e)},connected:function(e){return t.connected(e)},disconnected:function(e){return t.disconnected(e)},get peerId(){return t.peerId},get domain(){return e}}}var vo=function(){function e(e,t,n){var i=this;this.connection=e,this.settings=t,this.logger=n,this.protocolVersion=3,this.datePrefix="#T42_DATE#",this.datePrefixLen=this.datePrefix.length,this.dateMinLen=this.datePrefixLen+1,this.datePrefixFirstChar=this.datePrefix[0],this.registry=ji(),this._isLoggedIn=!1,this.shouldTryLogin=!0,this.initialLogin=!0,this.initialLoginAttempts=3,this.sessions=[],e.disconnected((function(){i.handleDisconnected()})),this.ping()}return Object.defineProperty(e.prototype,"isLoggedIn",{get:function(){return this._isLoggedIn},enumerable:!1,configurable:!0}),e.prototype.processStringMessage=function(e){var t=this,n=JSON.parse(e,(function(e,n){if("string"!=typeof n)return n;if(n.length<t.dateMinLen)return n;if(n[0]!==t.datePrefixFirstChar)return n;if(n.substring(0,t.datePrefixLen)!==t.datePrefix)return n;try{var i=parseInt(n.substring(t.datePrefixLen,n.length),10);return isNaN(i)?n:new Date(i)}catch(e){return n}}));return{msg:n,msgType:n.type}},e.prototype.createStringMessage=function(e){var t=Date.prototype.toJSON;try{var n=this.datePrefix;return Date.prototype.toJSON=function(){return n+this.getTime()},JSON.stringify(e)}finally{Date.prototype.toJSON=t}},e.prototype.processObjectMessage=function(e){if(!e.type)throw new Error("Object should have type property");return{msg:e,msgType:e.type}},e.prototype.createObjectMessage=function(e){return e},e.prototype.login=function(e,t){return oi(this,void 0,void 0,(function(){var n,i,o,r,s,a,c,u,d,h;return ri(this,(function(l){switch(l.label){case 0:if(this.logger.debug("logging in..."),this.loginConfig=e,this.loginConfig||(this.loginConfig={username:"",password:""}),this.shouldTryLogin=!0,n={},this.connection.gatewayToken=e.gatewayToken,!e.gatewayToken)return[3,5];if(!t)return[3,4];l.label=1;case 1:return l.trys.push([1,3,,4]),[4,this.getNewGWToken()];case 2:return u=l.sent(),e.gatewayToken=u,[3,4];case 3:return i=l.sent(),this.logger.warn("failed to get GW token when reconnecting ".concat((null==i?void 0:i.message)||i)),[3,4];case 4:return n.method="gateway-token",n.token=e.gatewayToken,this.connection.gatewayToken=e.gatewayToken,[3,10];case 5:return"sspi"!==e.flowName?[3,9]:(n.provider="win",n.method="access-token",e.flowCallback&&e.sessionId?(o=n,[4,e.flowCallback(e.sessionId,null)]):[3,7]);case 6:return o.token=l.sent().data.toString("base64"),[3,8];case 7:throw new Error("Invalid SSPI config");case 8:return[3,10];case 9: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}l.label=10;case 10:r={type:"hello",identity:this.settings.identity,authentication:n},e.sessionId&&(r.request_id=e.sessionId),this.globalDomain=mo("global",this.connection,this.logger.subLogger("global-domain"),["welcome","token","authentication-request"]),s={skipPeerId:!0},this.initialLogin&&(s.retryInterval=this.settings.reconnectInterval,s.maxRetries=this.settings.reconnectAttempts),l.label=11;case 11:l.trys.push([11,19,20,21]),a=void 0,l.label=12;case 12:return[4,this.globalDomain.send(r,void 0,s)];case 13:return"authentication-request"!==(c=l.sent()).type?[3,16]:(u=Buffer.from(c.authentication.token,"base64"),e.flowCallback&&e.sessionId?(d=r.authentication,[4,e.flowCallback(e.sessionId,u)]):[3,15]);case 14:d.token=l.sent().data.toString("base64"),l.label=15;case 15:return r.request_id=e.sessionId,[3,12];case 16:if("welcome"===c.type)return a=c,[3,18];throw"error"===c.type?new Error("Authentication failed: "+c.reason):new Error("Unexpected message type during authentication: "+c.type);case 17:return[3,12];case 18:return this.initialLogin=!1,this.logger.debug("login successful with peerId "+a.peer_id),this.connection.peerId=a.peer_id,this.connection.resolvedIdentity=a.resolved_identity,this.connection.availableDomains=a.available_domains,a.options&&(this.connection.token=a.options.access_token,this.connection.info=a.options.info),this.setLoggedIn(!0),[2,a.resolved_identity];case 19:throw h=l.sent(),this.logger.error("error sending hello message - "+(h.message||h.msg||h.reason||h),h),h;case 20:return e&&e.flowCallback&&e.sessionId&&e.flowCallback(e.sessionId,null),[7];case 21:return[2]}}))}))},e.prototype.logout=function(){return oi(this,void 0,void 0,(function(){var e;return ri(this,(function(t){switch(t.label){case 0:return this.logger.debug("logging out..."),this.shouldTryLogin=!1,this.pingTimer&&clearTimeout(this.pingTimer),e=this.sessions.map((function(e){e.leave()})),[4,Promise.all(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.loggedIn=function(e){return this._isLoggedIn&&e(),this.registry.add("onLoggedIn",e)},e.prototype.domain=function(e,t,n,i){var o=this.sessions.filter((function(t){return t.domain===e}))[0];return o||(o=mo(e,this.connection,t,n,i),this.sessions.push(o)),o},e.prototype.handleDisconnected=function(){var e=this;if(this.setLoggedIn(!1),this.shouldTryLogin&&this.initialLogin){if(this.initialLoginAttempts<=0)return;this.initialLoginAttempts--}if(this.logger.debug("disconnected - will try new login?"+this.shouldTryLogin),this.shouldTryLogin){if(!this.loginConfig)throw new Error("no login info");this.connection.login(this.loginConfig,!0).catch((function(){setTimeout(e.handleDisconnected.bind(e),e.settings.reconnectInterval||1e3)}))}},e.prototype.setLoggedIn=function(e){this._isLoggedIn=e,this._isLoggedIn&&this.registry.execute("onLoggedIn")},e.prototype.ping=function(){var e=this;this.shouldTryLogin&&(this._isLoggedIn&&this.connection.send({type:"ping"}),this.pingTimer=setTimeout((function(){e.ping()}),3e4))},e.prototype.authToken=function(){return this.globalDomain?this.globalDomain.send({type:"create-token"}).then((function(e){return e.token})):Promise.reject(new Error("no global domain session"))},e.prototype.getNewGWToken=function(){if(void 0!==typeof window){var e=window.glue42gd;if(e)return e.getGWToken()}return Promise.reject(new Error("not running in GD"))},e}(),yo=function(){function e(e){this.specsNames=[],this.messages={},this.subs={},this.subsRefCount={},this.specs={};for(var t=0,n=e;t<n.length;t++){var i=n[t];this.specs[i.name]=i,this.specsNames.push(i.name)}}return e.prototype.init=function(e){var t=this;this.connection=e;for(var n=0,i=this.specsNames;n<i.length;n++)for(var o=i[n],r=function(n){var i=s.subsRefCount[n];if(i||(i=0),i+=1,s.subsRefCount[n]=i,i>1)return"continue";var o=e.on(n,(function(e){return t.processMessage(n,e)}));s.subs[n]=o},s=this,a=0,c=this.specs[o].types;a<c.length;a++){r(c[a])}},e.prototype.processMessage=function(e,t){if(!this.isDone&&t)for(var n=0,i=this.specsNames;n<i.length;n++){var o=i[n];if(-1!==this.specs[o].types.indexOf(e)){var r=this.messages[o]||[];this.messages[o]=r,r.push(t)}}},e.prototype.drain=function(e,t){var n;t&&(this.messages[e]||[]).forEach(t),delete this.messages[e];for(var i=0,o=this.specs[e].types;i<o.length;i++){var r=o[i];this.subsRefCount[r]-=1,this.subsRefCount[r]<=0&&(null===(n=this.connection)||void 0===n||n.off(this.subs[r]),delete this.subs[r],delete this.subsRefCount[r])}delete this.specs[e],this.specs.length||(this.isDone=!0)},e}(),bo=function(e,t,n){return new Promise((function(i,o){var r=setTimeout((function(){var e=n||"Promise timeout hit: ".concat(t);o(e)}),t);new Promise(e).then((function(e){clearTimeout(r),i(e)})).catch((function(e){clearTimeout(r),o(e)}))}))},wo=function(){function e(e,t,n){this.settings=e,this.logger=t,this.identity=n,this.iAmConnected=!1,this.parentReady=!1,this.rejected=!1,this.children=[],this.extContentAvailable=!1,this.extContentConnecting=!1,this.extContentConnected=!1,this.parentInExtMode=!1,this.webNamespace="g42_core_web",this.parentPingTimeout=5e3,this.connectionRequestTimeout=7e3,this.defaultTargetString="*",this.registry=ji(),this.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:function(){}},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:this.handleClientUnload.bind(this)},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)}},this.extContentAvailable=!!window.glue42ext,this.setUpMessageListener(),this.setUpUnload(),this.setupPlatformUnloadListener(),this.parentType=window.name.includes("#wsp")?"workspace":void 0}return e.prototype.manualSetReadyState=function(){this.iAmConnected=!0,this.parentReady=!0},Object.defineProperty(e.prototype,"transportWindowId",{get:function(){return this.publicWindowId},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"communicationId",{get:function(){return this._communicationId},enumerable:!1,configurable:!0}),e.prototype.sendObject=function(e){return oi(this,void 0,void 0,(function(){return ri(this,(function(t){if(this.extContentConnected)return[2,window.postMessage({glue42ExtOut:e},this.defaultTargetString)];if(!this.port)throw new Error("Cannot send message, because the port was not opened yet");return this.port.postMessage(e),[2]}))}))},Object.defineProperty(e.prototype,"isObjectBasedTransport",{get:function(){return!0},enumerable:!1,configurable:!0}),e.prototype.onMessage=function(e){return this.registry.add("onMessage",e)},e.prototype.send=function(){return Promise.reject("not supported")},e.prototype.onConnectedChanged=function(e){return this.registry.add("onConnectedChanged",e)},e.prototype.open=function(){return oi(this,void 0,void 0,(function(){return ri(this,(function(e){switch(e.label){case 0:return this.logger.debug("opening a connection to the web platform gateway."),[4,this.connect()];case 1:return e.sent(),this.notifyStatusChanged(!0),[2]}}))}))},e.prototype.close=function(){var e,t,n={glue42core:{type:this.messages.gatewayDisconnect.name,data:{clientId:this.myClientId,ownWindowId:null===(e=this.identity)||void 0===e?void 0:e.windowId}}};return null===(t=this.port)||void 0===t||t.postMessage(n),this.parentReady=!1,this.notifyStatusChanged(!1,"manual reconnection"),Promise.resolve()},e.prototype.name=function(){return"web-platform"},e.prototype.reconnect=function(){return oi(this,void 0,void 0,(function(){return ri(this,(function(e){switch(e.label){case 0:return[4,this.close()];case 1:return e.sent(),[2,Promise.resolve()]}}))}))},e.prototype.initiateInternalConnection=function(){var e=this;return new Promise((function(t,n){e.logger.debug("opening an internal web platform connection"),e.port=e.settings.port,e.iAmConnected?e.logger.warn("cannot open a new connection, because this client is currently connected"):(e.port.onmessage=function(i){var o,r;if(!e.iAmConnected||(null===(o=i.data)||void 0===o?void 0:o.glue42core)){var s=null===(r=i.data)||void 0===r?void 0:r.glue42core;s&&(s.type===e.messages.gatewayInternalConnect.name&&s.success&&(e.publicWindowId=e.settings.windowId,e.identity&&e.publicWindowId&&(e.identity.windowId=e.publicWindowId,e.identity.instance=e.publicWindowId),t()),s.type===e.messages.gatewayInternalConnect.name&&s.error&&n(s.error))}else e.registry.execute("onMessage",i.data)},e.port.postMessage({glue42core:{type:e.messages.gatewayInternalConnect.name}}))}))},e.prototype.initiateRemoteConnection=function(e){var t=this;return bo((function(n,i){var o;t.connectionResolve=n,t.connectionReject=i,t.myClientId=null!==(o=t.myClientId)&&void 0!==o?o:go();var r=t.getMyWindowId()||go(),s={glue42core:{type:t.messages.connectionRequest.name,clientId:t.myClientId,clientType:"child",bridgeInstanceId:r,selfAssignedWindowId:t.selfAssignedWindowId}};if(t.logger.debug("sending connection request"),t.extContentConnecting)return s.glue42core.clientType="child",s.glue42core.bridgeInstanceId=t.myClientId,s.glue42core.parentWindowId=t.parentWindowId,window.postMessage(s,t.defaultTargetString);if(!e)throw new Error("Cannot send a connection request, because no glue target was specified!");e.postMessage(s,t.defaultTargetString)}),this.connectionRequestTimeout,"The connection to the target glue window timed out")},e.prototype.isParentCheckSuccess=function(e){return oi(this,void 0,void 0,(function(){return ri(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,e];case 1:return t.sent(),[2,{success:!0}];case 2:return t.sent(),[2,{success:!1}];case 3:return[2]}}))}))},e.prototype.setUpMessageListener=function(){var e=this;this.settings.port?this.logger.debug("skipping generic message listener, because this is an internal client"):window.addEventListener("message",(function(t){var n,i=null===(n=t.data)||void 0===n?void 0:n.glue42core;if(i&&!e.rejected)if(e.checkMessageTypeValid(i.type)){var o=i.type;e.logger.debug("received valid glue42core message of type: ".concat(o)),e.messages[o].handle(t)}else e.logger.error("cannot handle the incoming glue42 core message, because the type is invalid: ".concat(i.type))}))},e.prototype.setUpUnload=function(){var e=this;this.settings.port?this.logger.debug("skipping unload event listener, because this is an internal client"):window.addEventListener("beforeunload",(function(){var t,n;if(!e.extContentConnected){var i={glue42core:{type:e.messages.clientUnload.name,data:{clientId:e.myClientId,ownWindowId:null===(t=e.identity)||void 0===t?void 0:t.windowId}}};e.parent&&e.parent.postMessage(i,e.defaultTargetString),null===(n=e.port)||void 0===n||n.postMessage(i)}}))},e.prototype.handlePlatformReady=function(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"},e.prototype.handleConnectionAccepted=function(e){var t,n=null===(t=e.data)||void 0===t?void 0:t.glue42core;return this.myClientId===n.clientId?this.handleAcceptanceOfMyRequest(n):this.handleAcceptanceOfGrandChildRequest(n,e)},e.prototype.handleAcceptanceOfMyRequest=function(e){var t=this;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.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||go()),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=function(e){return t.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")},e.prototype.processExtContentConnection=function(e){var t=this;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",(function(e){var n,i=null===(n=e.data)||void 0===n?void 0:n.glue42ExtInc;i&&t.registry.execute("onMessage",i)})),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve},e.prototype.handleAcceptanceOfGrandChildRequest=function(e,t){if(this.extContentConnecting||this.extContentConnected)this.logger.debug("cannot process acceptance of a grandchild, because I am connected to a content script");else{this.logger.debug("handling a connection accepted signal targeted at a grandchild: ".concat(e.clientId));var n=this.children.find((function(t){return t.grandChildId===e.clientId}));n?(n.connected=!0,this.logger.debug("the grandchild connection for ".concat(e.clientId," is set up, forwarding the success message and the gateway port")),e.parentWindowId=this.publicWindowId,n.source.postMessage(t.data,n.origin,[e.port])):this.logger.error("cannot handle connection accepted for grandchild: ".concat(e.clientId,", because there is no grandchild with this id"))}},e.prototype.handleConnectionRejected=function(){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&&(this.connectionReject("The platform connection was rejected. Most likely because this window was not created by a glue API call"),delete this.connectionReject)},e.prototype.handleConnectionRequest=function(e){if(this.extContentConnecting)this.logger.debug("This connection request event is targeted at the extension content");else{var t=e.source,n=e.data.glue42core;if(!n.clientType||"grandChild"!==n.clientType)return this.rejectConnectionRequest(t,e.origin,"rejecting a connection request, because the source was not opened by a glue API call");if(!n.clientId)return this.rejectConnectionRequest(t,e.origin,"rejecting a connection request, because the source did not provide a valid id");if(!this.parent)return this.rejectConnectionRequest(t,e.origin,"Cannot forward the connection request, because no direct connection to the platform was found");this.logger.debug("handling a connection request for a grandchild: ".concat(n.clientId)),this.children.push({grandChildId:n.clientId,source:t,connected:!1,origin:e.origin}),this.logger.debug("grandchild: ".concat(n.clientId," is prepared, forwarding connection request to the platform")),this.parent.postMessage(e.data,this.defaultTargetString)}},e.prototype.handleParentPing=function(e){if(this.parentReady)if(this.iAmConnected){var t={glue42core:{type:this.messages.parentReady.name}};this.extContentConnected&&(t.glue42core.extMode={windowId:this.myClientId});var n=e.source;this.logger.debug("responding to a parent ping with a ready message"),n.postMessage(t,e.origin)}else this.logger.debug("i am not fully connected yet, I am ignoring the parent ping");else this.logger.debug("my parent is not ready, I am ignoring the parent ping")},e.prototype.setupPlatformUnloadListener=function(){var e=this;this.onMessage((function(t){"platformUnload"===t.type&&(e.logger.debug("detected a web platform unload"),e.parentReady=!1,e.notifyStatusChanged(!1,"Gateway unloaded"))}))},e.prototype.handleManualUnload=function(){var e,t,n={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:null===(e=this.identity)||void 0===e?void 0:e.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:n},this.defaultTargetString);null===(t=this.port)||void 0===t||t.postMessage(n)},e.prototype.handleClientUnload=function(e){var t=e.data.glue42core,n=null==t?void 0:t.data.clientId;n?this.children.find((function(e){return e.grandChildId===n}))?(this.logger.debug("handling grandchild unload for id: ".concat(n)),this.children=this.children.filter((function(e){return e.grandChildId!==n}))):this.logger.warn("cannot process grand child unload, because this client is unaware of this grandchild"):this.logger.warn("cannot process grand child unload, because the provided id was not valid")},e.prototype.handlePlatformPing=function(){},e.prototype.notifyStatusChanged=function(e,t){this.iAmConnected=e,this.registry.execute("onConnectedChanged",e,t)},e.prototype.checkMessageTypeValid=function(e){return"string"==typeof e&&!!this.messages[e]},e.prototype.rejectConnectionRequest=function(e,t,n){this.rejected=!0,this.logger.error(n);var i={glue42core:{type:this.messages.connectionRejected.name}};e.postMessage(i,t)},e.prototype.requestConnectionPermissionFromExt=function(){var e=this;return this.waitForContentScript().then((function(){return bo((function(t,n){e.extConnectionResolve=t,e.extConnectionReject=n;e.logger.debug("permission request to the extension content script was sent"),window.postMessage({glue42core:{type:"extSetupRequest"}},e.defaultTargetString)}),e.parentPingTimeout,"Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out")}))},e.prototype.handleExtConnectionResponse=function(e){var t;if(!(null===(t=e.data)||void 0===t?void 0:t.glue42core).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.")},e.prototype.handleExtSetupRequest=function(){},e.prototype.handleGatewayDisconnect=function(){},e.prototype.handleGatewayInternalConnect=function(){},e.prototype.waitForContentScript=function(){var e;return!!(null===(e=window.glue42ext)||void 0===e?void 0:e.content)?Promise.resolve():bo((function(e){window.addEventListener("Glue42EXTReady",(function(){e()}))}),this.connectionRequestTimeout,"The content script was available, but was never heard to be ready")},e.prototype.connect=function(){return oi(this,void 0,void 0,(function(){return ri(this,(function(e){switch(e.label){case 0:return this.settings.port?[4,this.initiateInternalConnection()]:[3,2];case 1:return e.sent(),this.logger.debug("internal web platform connection completed"),[2];case 2:return this.logger.debug("opening a client web platform connection"),[4,this.findParent()];case 3:return e.sent(),[4,this.initiateRemoteConnection(this.parent)];case 4:return e.sent(),this.logger.debug("the client is connected"),[2]}}))}))},e.prototype.findParent=function(){var e;return oi(this,void 0,void 0,(function(){var t,n,i,o;return ri(this,(function(r){switch(r.label){case 0:if(t="Cannot initiate glue, because this window was not opened or created by a glue client",n=this.getPossibleParentsInWindow(window),i=this.getPossibleParentsOutsideWindow(null===(e=window.top)||void 0===e?void 0:e.opener,window.top),!(o=new Set(si(si([],n,!0),i,!0))).size&&!this.extContentAvailable)throw new Error(t);return o.size||!this.extContentAvailable?[3,2]:[4,this.requestConnectionPermissionFromExt()];case 1:case 4:return r.sent(),[2];case 2:return[4,this.isParentCheckSuccess(this.confirmParent(Array.from(o)))];case 3:if(r.sent().success)return this.logger.debug("The default parent was found!"),[2];if(!this.extContentAvailable)throw new Error(t);return[4,this.requestConnectionPermissionFromExt()]}}))}))},e.prototype.getPossibleParentsInWindow=function(e){return e&&e!==e.top?si([e.parent],this.getPossibleParentsInWindow(e.parent),!0):[]},e.prototype.getPossibleParentsOutsideWindow=function(e,t){return e&&t&&e!==t?si(si([e],this.getPossibleParentsInWindow(e),!0),this.getPossibleParentsOutsideWindow(e.opener,e),!0):[]},e.prototype.confirmParent=function(e){var t=this,n=bo((function(n){t.parentPingResolve=n;var i={glue42core:{type:t.messages.platformPing.name}};t.parentPingInterval=setInterval((function(){e.forEach((function(e){e.postMessage(i,t.defaultTargetString)}))}),1e3)}),this.parentPingTimeout,"Cannot initiate glue, because this window was not opened or created by a glue client");return n.catch((function(){t.parentPingInterval&&(clearInterval(t.parentPingInterval),delete t.parentPingInterval)})),n},e.prototype.getMyWindowId=function(){var e;return"workspace"===this.parentType?window.name.substring(0,window.name.indexOf("#wsp")):window===window.top?(null===(e=window.name)||void 0===e?void 0:e.includes("g42"))?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||"g42-".concat(go()),this.selfAssignedWindowId):void 0},e}(),Io=function(){function e(e){void 0===e&&(e=0),this.minSequenceInterval=e,this.queue=[],this.isExecutingQueue=!1}return e.prototype.enqueue=function(e){var t=this;return new Promise((function(n,i){t.queue.push({action:e,resolve:n,reject:i}),t.executeQueue()}))},e.prototype.executeQueue=function(){return oi(this,void 0,void 0,(function(){var e,t,n;return ri(this,(function(i){switch(i.label){case 0:if(this.isExecutingQueue)return[2];this.isExecutingQueue=!0,i.label=1;case 1:if(!this.queue.length)return[3,7];if(!(e=this.queue.shift()))return this.isExecutingQueue=!1,[2];i.label=2;case 2:return i.trys.push([2,4,,5]),[4,e.action()];case 3:return t=i.sent(),e.resolve(t),[3,5];case 4:return n=i.sent(),e.reject(n),[3,5];case 5:return[4,this.intervalBreak()];case 6:return i.sent(),[3,1];case 7:return this.isExecutingQueue=!1,[2]}}))}))},e.prototype.intervalBreak=function(){var e=this;return new Promise((function(t){return setTimeout(t,e.minSequenceInterval)}))},e}(),Co=function(){function e(e,t){if(this.settings=e,this.logger=t,this.messageHandlers={},this.ids=1,this.registry=ji(),this._connected=!1,this.isTrace=!1,this._swapTransport=!1,this._switchInProgress=!1,this._transportSubscriptions=[],this._sequelizer=new Io,(e=e||{}).reconnectAttempts=e.reconnectAttempts||10,e.reconnectInterval=e.reconnectInterval||1e3,e.inproc)this.transport=new Ai(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new Ei(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new wo(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new qi(e,t.subLogger("ws"))}this.isTrace=t.canPublish("trace"),t.debug("starting with ".concat(this.transport.name()," transport")),this.protocol=new vo(this,e,t.subLogger("protocol"));var 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}return Object.defineProperty(e.prototype,"protocolVersion",{get:function(){var e;return null===(e=this.protocol)||void 0===e?void 0:e.protocolVersion},enumerable:!1,configurable:!0}),e.prototype.switchTransport=function(e){return oi(this,void 0,void 0,(function(){var t=this;return ri(this,(function(n){return[2,this._sequelizer.enqueue((function(){return oi(t,void 0,void 0,(function(){var t,n,i;return ri(this,(function(o){switch(o.label){case 0: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");return this.logger.trace("Starting transport switch with settings: ".concat(JSON.stringify(e))),t="secondary"===e.type?this.getNewSecondaryTransport(e):this._defaultTransport,this._targetTransport=t,this._targetAuth="secondary"===e.type?this.getNewSecondaryAuth(e):this._defaultAuth,n=this.verifyConnection(),this._swapTransport=!0,this._switchInProgress=!0,this.logger.trace("The new transport has been set, closing the current transport"),[4,this.transport.close()];case 1:o.sent(),o.label=2;case 2:return o.trys.push([2,4,,5]),[4,n];case 3:return o.sent(),i=this.transport===t,this.logger.info("The reconnection after the switch was completed. Was the switch a success: ".concat(i)),this._switchInProgress=!1,[2,{success:i}];case 4:return o.sent(),this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."),this.switchTransport({type:"default"}),this._switchInProgress=!1,[2,{success:!1}];case 5:return[2]}}))}))}))]}))}))},e.prototype.onLibReAnnounced=function(e){return this.registry.add("libReAnnounced",e)},e.prototype.setLibReAnnounced=function(e){this.registry.execute("libReAnnounced",e)},e.prototype.send=function(e,t){if(this.transport.sendObject&&this.transport.isObjectBasedTransport){var n=this.protocol.createObjectMessage(e);return this.isTrace&&this.logger.trace(">> ".concat(JSON.stringify(n))),this.transport.sendObject(n,t)}var i=this.protocol.createStringMessage(e);return this.isTrace&&this.logger.trace(">> ".concat(i)),this.transport.send(i,t)},e.prototype.on=function(e,t){e=e.toLowerCase(),void 0===this.messageHandlers[e]&&(this.messageHandlers[e]={});var n=this.ids++;return this.messageHandlers[e][n]=t,{type:e,id:n}},e.prototype.off=function(e){delete this.messageHandlers[e.type.toLowerCase()][e.id]},Object.defineProperty(e.prototype,"isConnected",{get:function(){return this.protocol.isLoggedIn},enumerable:!1,configurable:!0}),e.prototype.connected=function(e){var t=this;return this.protocol.loggedIn((function(){var n=t.transport.name();e(n)}))},e.prototype.disconnected=function(e){return this.registry.add("disconnected",e)},e.prototype.login=function(e,t){return oi(this,void 0,void 0,(function(){var n,i,o;return ri(this,(function(r){switch(r.label){case 0:this._defaultAuth||(this._defaultAuth=e),this._swapTransport&&(this.logger.trace("Detected a transport swap, swapping transports"),n=this.transportSwap(),e=null!=n?n:e),this.logger.trace("Starting login for transport: ".concat(this.transport.name()," and auth ").concat(JSON.stringify(e))),r.label=1;case 1:return r.trys.push([1,4,,5]),[4,this.transport.open()];case 2:return r.sent(),this.logger.trace("Transport: ".concat(this.transport.name()," opened, logging in")),Wi("connection").mark("transport-opened"),[4,this.protocol.login(e,t)];case 3:return i=r.sent(),this.logger.trace("Logged in with identity: ".concat(JSON.stringify(i))),Wi("connection").mark("protocol-logged-in"),[2,i];case 4:throw o=r.sent(),this._switchInProgress&&(this.logger.trace("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),new Error(o);case 5:return[2]}}))}))},e.prototype.logout=function(){return oi(this,void 0,void 0,(function(){return ri(this,(function(e){switch(e.label){case 0:return[4,this.protocol.logout()];case 1:return e.sent(),[4,this.transport.close()];case 2:return e.sent(),[2]}}))}))},e.prototype.loggedIn=function(e){return this.protocol.loggedIn(e)},e.prototype.domain=function(e,t,n){return this.protocol.domain(e,this.logger.subLogger("domain=".concat(e)),t,n)},e.prototype.authToken=function(){return this.protocol.authToken()},e.prototype.reconnect=function(){return this.transport.reconnect()},e.prototype.distributeMessage=function(e,t){var n=this,i=this.messageHandlers[t.toLowerCase()];void 0!==i&&Object.keys(i).forEach((function(t){var o=i[t];if(void 0!==o)try{o(e)}catch(e){try{n.logger.error("Message handler failed with ".concat(e.stack),e)}catch(t){console.log("Message handler failed",e)}}}))},e.prototype.handleConnectionChanged=function(e){this._connected!==e&&(this._connected=e,e?(this.settings.replaySpecs&&this.settings.replaySpecs.length&&(this.replayer=new yo(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):this.registry.execute("disconnected"))},e.prototype.handleTransportMessage=function(e){var t;t="string"==typeof e?this.protocol.processStringMessage(e):this.protocol.processObjectMessage(e),this.isTrace&&this.logger.trace("<< ".concat(JSON.stringify(t))),this.distributeMessage(t.msg,t.msgType)},e.prototype.verifyConnection=function(){var e=this;return bo((function(t){var n,i,o,r=(i=function(){n&&n(),t()},o=2,function(){0==--o&&i()});n=e.onLibReAnnounced((function(e){return"interop"===e.name||"contexts"===e.name?r():void 0}))}),1e4,"Transport switch timed out waiting for all libraries to be re-announced")},e.prototype.getNewSecondaryTransport=function(e){var t;if(!(null===(t=e.transportConfig)||void 0===t?void 0:t.url))throw new Error("Missing secondary transport URL.");return new qi(Object.assign({},this.settings,{ws:e.transportConfig.url,reconnectAttempts:1}),this.logger.subLogger("ws-secondary"))},e.prototype.getNewSecondaryAuth=function(e){var t;if(!(null===(t=e.transportConfig)||void 0===t?void 0:t.auth))throw new Error("Missing secondary transport auth information.");return e.transportConfig.auth},e.prototype.transportSwap=function(){if(this._swapTransport=!1,this._targetTransport&&this._targetAuth){this._transportSubscriptions.forEach((function(e){return e()})),this._transportSubscriptions=[],this.transport=this._targetTransport;var 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}this.logger.warn("Error while switching transports - either the target transport or auth is not defined: transport defined -> ".concat(!!this._defaultTransport,", auth defined -> ").concat(!!this._targetAuth,". Staying on the current one."))},e.prototype.prepareDefaultSwap=function(){var e=this;this._transportSubscriptions.forEach((function(e){return e()})),this._transportSubscriptions=[],this.transport.close().catch((function(t){return e.logger.warn("Error closing the ".concat(e.transport.name()," transport after a failed connection attempt: ").concat(JSON.stringify(t)))})),this._targetTransport=this._defaultTransport,this._targetAuth=this._defaultAuth,this._swapTransport=!0},e}(),So=["trace","debug","info","warn","error","off"],xo=function(){function e(e,t,n){this.name=e,this.parent=t,this.subLoggers=[],this.logFn=console,this.customLogFn=!1,this.name=e,this.path=t?"".concat(t.path,".").concat(e):e,this.loggerFullName="[".concat(this.path,"]"),this.includeTimeAndLevel=!n,n&&(this.logFn=n,this.customLogFn=!0)}return e.prototype.subLogger=function(t){var n=this.subLoggers.filter((function(e){return e.name===t}))[0];if(void 0!==n)return n;Object.keys(this).forEach((function(e){if(e===t)throw new Error("This sub logger name is not allowed.")}));var i=new e(t,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(i),i},e.prototype.publishLevel=function(e){var t;return e&&(this._publishLevel=e),this._publishLevel||(null===(t=this.parent)||void 0===t?void 0:t.publishLevel())},e.prototype.consoleLevel=function(e){var t;return e&&(this._consoleLevel=e),this._consoleLevel||(null===(t=this.parent)||void 0===t?void 0:t.consoleLevel())},e.prototype.log=function(e,t,n){this.publishMessage(t||"info",e,n)},e.prototype.trace=function(e){this.log(e,"trace")},e.prototype.debug=function(e){this.log(e,"debug")},e.prototype.info=function(e){this.log(e,"info")},e.prototype.warn=function(e){this.log(e,"warn")},e.prototype.error=function(e,t){this.log(e,"error")},e.prototype.canPublish=function(e,t){return So.indexOf(e)>=So.indexOf(t||this.consoleLevel()||"trace")},e.prototype.publishMessage=function(t,n,i){var o=this.loggerFullName;if("error"===t&&!i){var r=new Error;r.stack&&(n=n+"\n"+r.stack.split("\n").slice(3).join("\n"))}if(this.canPublish(t,this.publishLevel())){var s=e.Interop;if(s)try{s.methods({name:e.InteropMethodName}).length>0&&s.invoke(e.InteropMethodName,{msg:"".concat(n),logger:o,level:t})}catch(e){}}if(this.canPublish(t)){var a="";if(this.includeTimeAndLevel){var c=new Date,u="".concat(c.getHours(),":").concat(c.getMinutes(),":").concat(c.getSeconds(),":").concat(c.getMilliseconds());a="[".concat(u,"] [").concat(t,"] ")}var d="".concat(a).concat(o,": ").concat(n);switch(t){case"trace":this.logFn.debug(d);break;case"debug":this.logFn.debug?this.logFn.debug(d):this.logFn.log(d);break;case"info":this.logFn.info(d);break;case"warn":this.logFn.warn(d);break;case"error":this.logFn.error(d,i)}}},e.InteropMethodName="T42.AppLogger.Log",e}(),_o="create-context",Po="created",To="destroyed",ko="context-created",Mo="context-added",Ro="subscribe-context",jo="subscribed-context",Ao="unsubscribe-context",Eo="destroy-context",Oo="context-destroyed",No="update-context",Do="context-updated",Wo="joined",Lo={get name(){return"context"},get types(){return[_o,Po,To,ko,Mo,Ro,jo,Ao,Eo,Oo,No,Do,Wo]}},qo="6.0.4";var Fo=function(){function e(e,t,n,i){this.updateCallbacks={},this.contextId=e,this.name=t,this.isAnnounced=n,this.activityId=i,this.context={}}return e.prototype.hasCallbacks=function(){return Object.keys(this.updateCallbacks).length>0},e.prototype.getState=function(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0},e}(),Go={};!function(e,t){var n=200,i="__lodash_hash_undefined__",o=9007199254740991,r="[object Arguments]",s="[object Boolean]",a="[object Date]",c="[object Function]",u="[object GeneratorFunction]",d="[object Map]",h="[object Number]",l="[object Object]",p="[object Promise]",f="[object RegExp]",g="[object Set]",m="[object String]",v="[object Symbol]",y="[object WeakMap]",b="[object ArrayBuffer]",w="[object DataView]",I="[object Float32Array]",C="[object Float64Array]",S="[object Int8Array]",x="[object Int16Array]",_="[object Int32Array]",P="[object Uint8Array]",T="[object Uint8ClampedArray]",k="[object Uint16Array]",M="[object Uint32Array]",R=/\w*$/,j=/^\[object .+?Constructor\]$/,A=/^(?:0|[1-9]\d*)$/,E={};E[r]=E["[object Array]"]=E[b]=E[w]=E[s]=E[a]=E[I]=E[C]=E[S]=E[x]=E[_]=E[d]=E[h]=E[l]=E[f]=E[g]=E[m]=E[v]=E[P]=E[T]=E[k]=E[M]=!0,E["[object Error]"]=E[c]=E[y]=!1;var O="object"==typeof ki&&ki&&ki.Object===Object&&ki,N="object"==typeof self&&self&&self.Object===Object&&self,D=O||N||Function("return this")(),W=t&&!t.nodeType&&t,L=W&&e&&!e.nodeType&&e,q=L&&L.exports===W;function F(e,t){return e.set(t[0],t[1]),e}function G(e,t){return e.add(t),e}function U(e,t,n,i){var o=-1,r=e?e.length:0;for(i&&r&&(n=e[++o]);++o<r;)n=t(n,e[o],o,e);return n}function B(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}function $(e){var t=-1,n=Array(e.size);return e.forEach((function(e,i){n[++t]=[i,e]})),n}function J(e,t){return function(n){return e(t(n))}}function H(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n}var K,V=Array.prototype,z=Function.prototype,Q=Object.prototype,X=D["__core-js_shared__"],Y=(K=/[^.]+$/.exec(X&&X.keys&&X.keys.IE_PROTO||""))?"Symbol(src)_1."+K:"",Z=z.toString,ee=Q.hasOwnProperty,te=Q.toString,ne=RegExp("^"+Z.call(ee).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ie=q?D.Buffer:void 0,oe=D.Symbol,re=D.Uint8Array,se=J(Object.getPrototypeOf,Object),ae=Object.create,ce=Q.propertyIsEnumerable,ue=V.splice,de=Object.getOwnPropertySymbols,he=ie?ie.isBuffer:void 0,le=J(Object.keys,Object),pe=Le(D,"DataView"),fe=Le(D,"Map"),ge=Le(D,"Promise"),me=Le(D,"Set"),ve=Le(D,"WeakMap"),ye=Le(Object,"create"),be=Be(pe),we=Be(fe),Ie=Be(ge),Ce=Be(me),Se=Be(ve),xe=oe?oe.prototype:void 0,_e=xe?xe.valueOf:void 0;function Pe(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 Me(e){this.__data__=new Te(e)}function Re(e,t){var n=Je(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&He(e)}(e)&&ee.call(e,"callee")&&(!ce.call(e,"callee")||te.call(e)==r)}(e)?function(e,t){for(var n=-1,i=Array(e);++n<e;)i[n]=t(n);return i}(e.length,String):[],i=n.length,o=!!i;for(var s in e)!t&&!ee.call(e,s)||o&&("length"==s||Ge(s,i))||n.push(s);return n}function je(e,t,n){var i=e[t];ee.call(e,t)&&$e(i,n)&&(void 0!==n||t in e)||(e[t]=n)}function Ae(e,t){for(var n=e.length;n--;)if($e(e[n][0],t))return n;return-1}function Ee(e,t,n,i,o,p,y){var j;if(i&&(j=p?i(e,o,p,y):i(e)),void 0!==j)return j;if(!ze(e))return e;var A=Je(e);if(A){if(j=function(e){var t=e.length,n=e.constructor(t);t&&"string"==typeof e[0]&&ee.call(e,"index")&&(n.index=e.index,n.input=e.input);return n}(e),!t)return function(e,t){var n=-1,i=e.length;t||(t=Array(i));for(;++n<i;)t[n]=e[n];return t}(e,j)}else{var O=Fe(e),N=O==c||O==u;if(Ke(e))return function(e,t){if(t)return e.slice();var n=new e.constructor(e.length);return e.copy(n),n}(e,t);if(O==l||O==r||N&&!p){if(B(e))return p?e:{};if(j=function(e){return"function"!=typeof e.constructor||Ue(e)?{}:(t=se(e),ze(t)?ae(t):{});var t}(N?{}:e),!t)return function(e,t){return De(e,qe(e),t)}(e,function(e,t){return e&&De(t,Qe(t),e)}(j,e))}else{if(!E[O])return p?e:{};j=function(e,t,n,i){var o=e.constructor;switch(t){case b:return Ne(e);case s:case a:return new o(+e);case w:return function(e,t){var n=t?Ne(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}(e,i);case I:case C:case S:case x:case _:case P:case T:case k:case M:return function(e,t){var n=t?Ne(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($(e),!0):$(e);return U(i,F,new e.constructor)}(e,i,n);case h:case m:return new o(e);case f:return function(e){var t=new e.constructor(e.source,R.exec(e));return t.lastIndex=e.lastIndex,t}(e);case g:return function(e,t,n){var i=t?n(H(e),!0):H(e);return U(i,G,new e.constructor)}(e,i,n);case v:return r=e,_e?Object(_e.call(r)):{}}var r}(e,O,Ee,t)}}y||(y=new Me);var D=y.get(e);if(D)return D;if(y.set(e,j),!A)var W=n?function(e){return function(e,t,n){var i=t(e);return Je(e)?i:function(e,t){for(var n=-1,i=t.length,o=e.length;++n<i;)e[o+n]=t[n];return e}(i,n(e))}(e,Qe,qe)}(e):Qe(e);return function(e,t){for(var n=-1,i=e?e.length:0;++n<i&&!1!==t(e[n],n,e););}(W||e,(function(o,r){W&&(o=e[r=o]),je(j,r,Ee(o,t,n,i,r,e,y))})),j}function Oe(e){return!(!ze(e)||(t=e,Y&&Y in t))&&(Ve(e)||B(e)?ne:j).test(Be(e));var t}function Ne(e){var t=new e.constructor(e.byteLength);return new re(t).set(new re(e)),t}function De(e,t,n,i){n||(n={});for(var o=-1,r=t.length;++o<r;){var s=t[o],a=i?i(n[s],e[s],s,n,e):void 0;je(n,s,void 0===a?e[s]:a)}return n}function We(e,t){var n,i,o=e.__data__;return("string"==(i=typeof(n=t))||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==n:null===n)?o["string"==typeof t?"string":"hash"]:o.map}function Le(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Oe(n)?n:void 0}Pe.prototype.clear=function(){this.__data__=ye?ye(null):{}},Pe.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},Pe.prototype.get=function(e){var t=this.__data__;if(ye){var n=t[e];return n===i?void 0:n}return ee.call(t,e)?t[e]:void 0},Pe.prototype.has=function(e){var t=this.__data__;return ye?void 0!==t[e]:ee.call(t,e)},Pe.prototype.set=function(e,t){return this.__data__[e]=ye&&void 0===t?i: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():ue.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 Pe,map:new(fe||Te),string:new Pe}},ke.prototype.delete=function(e){return We(this,e).delete(e)},ke.prototype.get=function(e){return We(this,e).get(e)},ke.prototype.has=function(e){return We(this,e).has(e)},ke.prototype.set=function(e,t){return We(this,e).set(e,t),this},Me.prototype.clear=function(){this.__data__=new Te},Me.prototype.delete=function(e){return this.__data__.delete(e)},Me.prototype.get=function(e){return this.__data__.get(e)},Me.prototype.has=function(e){return this.__data__.has(e)},Me.prototype.set=function(e,t){var i=this.__data__;if(i instanceof Te){var o=i.__data__;if(!fe||o.length<n-1)return o.push([e,t]),this;i=this.__data__=new ke(o)}return i.set(e,t),this};var qe=de?J(de,Object):function(){return[]},Fe=function(e){return te.call(e)};function Ge(e,t){return!!(t=null==t?o:t)&&("number"==typeof e||A.test(e))&&e>-1&&e%1==0&&e<t}function Ue(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Q)}function Be(e){if(null!=e){try{return Z.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function $e(e,t){return e===t||e!=e&&t!=t}(pe&&Fe(new pe(new ArrayBuffer(1)))!=w||fe&&Fe(new fe)!=d||ge&&Fe(ge.resolve())!=p||me&&Fe(new me)!=g||ve&&Fe(new ve)!=y)&&(Fe=function(e){var t=te.call(e),n=t==l?e.constructor:void 0,i=n?Be(n):void 0;if(i)switch(i){case be:return w;case we:return d;case Ie:return p;case Ce:return g;case Se:return y}return t});var Je=Array.isArray;function He(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=o}(e.length)&&!Ve(e)}var Ke=he||function(){return!1};function Ve(e){var t=ze(e)?te.call(e):"";return t==c||t==u}function ze(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Qe(e){return He(e)?Re(e):function(e){if(!Ue(e))return le(e);var t=[];for(var n in Object(e))ee.call(e,n)&&"constructor"!=n&&t.push(n);return t}(e)}e.exports=function(e){return Ee(e,!0,!0)}}({get exports(){return Go},set exports(e){Go=e}},Go);var Uo=Go;function Bo(e,t,n){try{if((null==n?void 0:n.canPublish("trace"))&&(null==n||n.trace("applying context delta ".concat(JSON.stringify(t)," on context ").concat(JSON.stringify(e)))),!t)return e;if(t.reset)return e=ii({},t.reset);if(e=$o(e,void 0),t.commands){for(var i=0,o=t.commands;i<o.length;i++){var r=o[i];"remove"===r.type?zo(e,r.path):"set"===r.type&&Ko(e,r.value,r.path)}return e}var s=t.added,a=t.updated,c=t.removed;return s&&Object.keys(s).forEach((function(t){e[t]=s[t]})),a&&Object.keys(a).forEach((function(t){Jo(t,e,a)})),c&&c.forEach((function(t){delete e[t]})),e}catch(i){return null==n||n.error("error applying context delta ".concat(JSON.stringify(t)," on context ").concat(JSON.stringify(e)),i),e}}function $o(e,t){return Uo(e)}var Jo=function(e,t,n){var i=n[e];if(void 0===i)return t;var o=t[e];return o&&i?"string"==typeof o||"number"==typeof o||"boolean"==typeof o||"string"==typeof i||"number"==typeof i||"boolean"==typeof i||Array.isArray(o)||Array.isArray(i)?(t[e]=i,t):(t[e]=Object.assign({},o,i),t):(t[e]=i,t)};function Ho(e,t){if(e===t)return!0;if(!(e instanceof Object&&t instanceof Object))return!1;if(e.constructor!==t.constructor)return!1;for(var 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(!Ho(e[n],t[n]))return!1}}for(var n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}function Ko(e,t,n){var i,o=n.split(".");for(i=0;i<o.length-1;i++)e[o[i]]||(e[o[i]]={}),"object"!=typeof e[o[i]]&&(e[o[i]]={}),e=e[o[i]];e[o[i]]=t}function Vo(e,t){return Object.keys(t).every((function(n){return"object"==typeof t[n]?Vo((null==e?void 0:e[n])||{},t[n]||{}):t[n]===(null==e?void 0:e[n])}))}function zo(e,t){var n,i=t.split(".");for(n=0;n<i.length-1;n++){if(!e[i[n]])return;e=e[i[n]]}delete e[i[n]]}var Qo,Xo=function(){function e(e){var t,n=this;this._contextNameToData={},this._gw3Subscriptions=[],this._nextCallbackSubscriptionNumber=0,this._creationPromises={},this._contextNameToId={},this._contextIdToName={},this._protocolVersion=void 0,this._contextsTempCache={},this._contextsSubscriptionsCache=[],this._connection=e.connection,this._logger=e.logger,this._trackAllContexts=e.trackAllContexts,this._reAnnounceKnownContexts=e.reAnnounceKnownContexts,this._gw3Session=this._connection.domain("global",[ko,jo,Oo,Do]),this._gw3Session.disconnected(this.resetState.bind(this)),this._gw3Session.onJoined((function(e){if(e)return n._reAnnounceKnownContexts?void n.reInitiateState().then((function(){return n._connection.setLibReAnnounced({name:"contexts"})})):n._connection.setLibReAnnounced({name:"contexts"})})),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),null===(t=this._connection.replayer)||void 0===t||t.drain(Lo.name,(function(e){var t=e.type;t&&(t===ko||t===Mo||t===Po?n.handleContextCreatedMessage(e):t===jo||t===Do||t===Wo?n.handleContextUpdatedMessage(e):t!==Oo&&t!==To||n.handleContextDestroyedMessage(e))}))}return Object.defineProperty(e.prototype,"protocolVersion",{get:function(){var e;if(!this._protocolVersion){var t=this._connection.availableDomains.find((function(e){return"context"===e.uri}));this._protocolVersion=null!==(e=null==t?void 0:t.version)&&void 0!==e?e:1}return this._protocolVersion},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"setPathSupported",{get:function(){return this.protocolVersion>=2},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){for(var e=0,t=this._gw3Subscriptions;e<t.length;e++){var n=t[e];this._connection.off(n)}for(var i in this._gw3Subscriptions.length=0,this._contextNameToData)this._contextNameToId.hasOwnProperty(i)&&delete this._contextNameToData[i]},e.prototype.createContext=function(e,t){var n=this;return e in this._creationPromises||(this._creationPromises[e]=this._gw3Session.send({type:_o,domain:"global",name:e,data:t,lifetime:"retained"}).then((function(i){n._contextNameToId[e]=i.context_id,n._contextIdToName[i.context_id]=e;var o=n._contextNameToData[e]||new Fo(i.context_id,e,!0,void 0);return o.isAnnounced=!0,o.name=e,o.contextId=i.context_id,o.context=i.data||$o(t),o.hasReceivedSnapshot=!0,n._contextNameToData[e]=o,delete n._creationPromises[e],i.context_id}))),this._creationPromises[e]},e.prototype.all=function(){var e=this;return Object.keys(this._contextNameToData).filter((function(t){return e._contextNameToData[t].isAnnounced}))},e.prototype.update=function(e,t){var n;return oi(this,void 0,void 0,(function(){var i,o,r,s=this;return ri(this,(function(a){switch(a.label){case 0:return t&&(t=$o(t)),e in this._creationPromises?[4,this._creationPromises[e]]:[3,2];case 1:a.sent(),a.label=2;case 2:return(i=this._contextNameToData[e])&&i.isAnnounced?(o=i.context,i.hasCallbacks()?[3,4]:[4,this.get(i.name)]):[2,this.createContext(e,t)];case 3:o=a.sent(),a.label=4;case 4:return r=2===this.protocolVersion?this.calculateContextDeltaV2(o,t):this.calculateContextDeltaV1(o,t),Object.keys(r.added).length||Object.keys(r.updated).length||r.removed.length||(null===(n=r.commands)||void 0===n?void 0:n.length)?[2,this._gw3Session.send({type:No,domain:"global",context_id:i.contextId,delta:r},{},{skipPeerId:!1}).then((function(e){s.handleUpdated(i,r,{updaterId:e.peer_id})}))]:[2,Promise.resolve()]}}))}))},e.prototype.set=function(e,t){return oi(this,void 0,void 0,(function(){var n,i=this;return ri(this,(function(o){switch(o.label){case 0:return t&&(t=$o(t)),e in this._creationPromises?[4,this._creationPromises[e]]:[3,2];case 1:o.sent(),o.label=2;case 2:return(n=this._contextNameToData[e])&&n.isAnnounced?[2,this._gw3Session.send({type:No,domain:"global",context_id:n.contextId,delta:{reset:t}},{},{skipPeerId:!1}).then((function(e){i.handleUpdated(n,{reset:t,added:{},removed:[],updated:{}},{updaterId:e.peer_id})}))]:[2,this.createContext(e,t)]}}))}))},e.prototype.setPath=function(e,t,n){return this.setPathSupported?this.setPaths(e,[{path:t,value:n}]):Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later")},e.prototype.setPaths=function(e,t){return oi(this,void 0,void 0,(function(){var n,i,o,r,s,a,c,u,d=this;return ri(this,(function(h){switch(h.label){case 0:return this.setPathSupported?(t&&(t=$o(t)),e in this._creationPromises?[4,this._creationPromises[e]]:[3,2]):[2,Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later")];case 1:h.sent(),h.label=2;case 2:if(!(n=this._contextNameToData[e])||!n.isAnnounced){for(i={},o=0,r=t;o<r.length;o++)u=r[o],Ko(i,u.value,u.path);return[2,this.createContext(e,i)]}for(s=[],a=0,c=t;a<c.length;a++)null===(u=c[a]).value?s.push({type:"remove",path:u.path}):s.push({type:"set",path:u.path,value:u.value});return[2,this._gw3Session.send({type:No,domain:"global",context_id:n.contextId,delta:{commands:s}},{},{skipPeerId:!1}).then((function(e){d.handleUpdated(n,{added:{},removed:[],updated:{},commands:s},{updaterId:e.peer_id})}))]}}))}))},e.prototype.get=function(e){var t;return oi(this,void 0,void 0,(function(){var n,i,o=this;return ri(this,(function(r){switch(r.label){case 0:return e in this._creationPromises?[4,this._creationPromises[e]]:[3,2];case 1:r.sent(),r.label=2;case 2:return(n=this._contextNameToData[e])&&n.isAnnounced?!n||n.hasCallbacks()&&n.hasReceivedSnapshot?(i=null!==(t=null==n?void 0:n.context)&&void 0!==t?t:{},[2,Promise.resolve($o(i))]):[2,new Promise((function(t){o.subscribe(e,(function(e,n,i,r){o.unsubscribe(r),t(e)}))}))]:[2,Promise.resolve({})]}}))}))},e.prototype.subscribe=function(e,t,n){return oi(this,void 0,void 0,(function(){var i,o,r,s,a=this;return ri(this,(function(c){switch(c.label){case 0:return e in this._creationPromises?[4,this._creationPromises[e]]:[3,2];case 1:c.sent(),c.label=2;case 2:return i=void 0===n?this._nextCallbackSubscriptionNumber:n,void 0===n&&(this._nextCallbackSubscriptionNumber+=1),this._contextsSubscriptionsCache.every((function(e){return e.subKey!==a._nextCallbackSubscriptionNumber}))&&this._contextsSubscriptionsCache.push({contextName:e,subKey:i,callback:t}),(o=this._contextNameToData[e])&&o.isAnnounced?(r=o.hasCallbacks(),o.updateCallbacks[i]=t,r||o.joinedActivity||o.context&&o.sentExplicitSubscription?(o.hasReceivedSnapshot&&(s=$o(o.context),t(s,s,[],i)),[2,Promise.resolve(i)]):[2,this.sendSubscribe(o).then((function(){return i}))]):(o=o||new Fo(void 0,e,!1,void 0),this._contextNameToData[e]=o,o.updateCallbacks[i]=t,[2,Promise.resolve(i)])}}))}))},e.prototype.unsubscribe=function(e){this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter((function(t){return t.subKey!==e}));for(var t=0,n=Object.keys(this._contextNameToData);t<n.length;t++){var i=n[t],o=this._contextNameToData[i];if(!o)return;var r=o.hasCallbacks();delete o.updateCallbacks[e],o.isAnnounced&&r&&!o.hasCallbacks()&&o.sentExplicitSubscription&&this.sendUnsubscribe(o),o.isAnnounced||o.hasCallbacks()||delete this._contextNameToData[i]}},e.prototype.destroy=function(e){return oi(this,void 0,void 0,(function(){var t;return ri(this,(function(n){switch(n.label){case 0:return e in this._creationPromises?[4,this._creationPromises[e]]:[3,2];case 1:n.sent(),n.label=2;case 2:return(t=this._contextNameToData[e])?[2,this._gw3Session.send({type:Eo,domain:"global",context_id:t.contextId}).then((function(e){}))]:[2,Promise.reject("context with ".concat(e," does not exist"))]}}))}))},e.prototype.handleUpdated=function(e,t,n){var i=e.context;e.context=Bo(e.context,t,this._logger),e.hasReceivedSnapshot=!0,this._contextNameToData[e.name]!==e||Ho(i,e.context)||this.invokeUpdateCallbacks(e,t,n)},e.prototype.subscribeToContextCreatedMessages=function(){for(var e=0,t=[Mo,ko,Po];e<t.length;e++){var n=t[e],i=this._connection.on(n,this.handleContextCreatedMessage.bind(this));this._gw3Subscriptions.push(i)}},e.prototype.handleContextCreatedMessage=function(e){var t=this,n=e.type;n===Po?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):n===Mo&&(this._contextNameToId[e.name]=e.context_id,this._contextIdToName[e.context_id]=e.name);var i=this._contextIdToName[e.context_id];if(!i)throw new Error("Received created event for context with unknown name: "+e.context_id);if(!this._contextNameToId[i])throw new Error("Received created event for context with unknown id: "+e.context_id);var o=this._contextNameToData[i];if(o){if(o.isAnnounced)return;if(!o.hasCallbacks())throw new Error("Assertion failure: contextData.hasCallbacks()");o.isAnnounced=!0,o.contextId=e.context_id,o.activityId=e.activity_id,o.sentExplicitSubscription||this.sendSubscribe(o)}else this._contextNameToData[i]=o=new Fo(e.context_id,i,!0,e.activity_id),this._trackAllContexts&&this.subscribe(i,(function(){})).then((function(e){return t._systemContextsSubKey=e}))},e.prototype.subscribeToContextUpdatedMessages=function(){for(var e=0,t=[Do,jo,Wo];e<t.length;e++){var n=t[e],i=this._connection.on(n,this.handleContextUpdatedMessage.bind(this));this._gw3Subscriptions.push(i)}},e.prototype.handleContextUpdatedMessage=function(e){var t=e.type,n=e.context_id,i=this._contextNameToData[this._contextIdToName[n]],o=!i||!i.isAnnounced;if(t===Wo)i||(i=this._contextNameToData[e.activity_id]||new Fo(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===jo?((i=i||new Fo(n,e.name,!0,void 0)).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: ".concat(n)));var r=i.context;if(i.hasReceivedSnapshot=!0,t===jo)i.context=e.data||{};else if(t===Wo)i.context=e.context_snapshot||{};else{if(t!==Do)throw new Error("Unrecognized context update message "+t);i.context=Bo(i.context,e.delta,this._logger)}!o&&Ho(i.context,r)&&t!==jo||this.invokeUpdateCallbacks(i,e.delta,{updaterId:e.updater_id})},e.prototype.invokeUpdateCallbacks=function(e,t,n){if((t=t||{added:{},updated:{},reset:{},removed:[]}).commands){t.added=t.updated=t.reset={},t.removed=[];for(var i=0,o=t.commands;i<o.length;i++){var r=o[i];"remove"===r.type?(-1===r.path.indexOf(".")&&t.removed.push(r.path),Ko(t.updated,null,r.path)):"set"===r.type&&Ko(t.updated,r.value,r.path)}}for(var s in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(s))try{(0,e.updateCallbacks[s])($o(e.context),$o(Object.assign({},t.added||{},t.updated||{},t.reset||{})),t.removed,parseInt(s,10),n)}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}},e.prototype.subscribeToContextDestroyedMessages=function(){for(var e=0,t=[Oo,To];e<t.length;e++){var n=t[e],i=this._connection.on(n,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(i)}},e.prototype.handleContextDestroyedMessage=function(e){var t,n;if(e.type===To){if(n=e.activity_id,!(t=this._contextNameToId[n]))return void this._logger.error("Received 'destroyed' for unknown activity: ".concat(e.activity_id))}else if(t=e.context_id,!(n=this._contextIdToName[t]))return void this._logger.error("Received 'destroyed' for unknown context: ".concat(e.context_id));delete this._contextIdToName[t],delete this._contextNameToId[n];var i=this._contextNameToData[n];delete this._contextNameToData[n],i&&i.isAnnounced||this._logger.error("Received 'destroyed' for unknown context: ".concat(t))},e.prototype.sendSubscribe=function(e){return e.sentExplicitSubscription=!0,this._gw3Session.send({type:Ro,domain:"global",context_id:e.contextId}).then((function(e){}))},e.prototype.sendUnsubscribe=function(e){return e.sentExplicitSubscription=!1,this._gw3Session.send({type:Ao,domain:"global",context_id:e.contextId}).then((function(e){}))},e.prototype.calculateContextDeltaV1=function(e,t){var n={added:{},updated:{},removed:[],reset:void 0};if(e)for(var i=0,o=Object.keys(e);i<o.length;i++){var r=o[i];-1===Object.keys(t).indexOf(r)||null===t[r]||Ho(e[r],t[r])||(n.updated[r]=t[r])}for(var s=0,a=Object.keys(t);s<a.length;s++){r=a[s];e&&-1!==Object.keys(e).indexOf(r)?null===t[r]&&n.removed.push(r):null!==t[r]&&(n.added[r]=t[r])}return n},e.prototype.calculateContextDeltaV2=function(e,t){for(var n,i,o={added:{},updated:{},removed:[],reset:void 0,commands:[]},r=0,s=Object.keys(t);r<s.length;r++){var a=s[r];if(null!==t[a])Ho(e?e[a]:null,t[a])||null===(n=o.commands)||void 0===n||n.push({type:"set",path:a,value:t[a]});else null===(i=o.commands)||void 0===i||i.push({type:"remove",path:a})}return o},e.prototype.resetState=function(){for(var e=this,t=0,n=this._gw3Subscriptions;t<n.length;t++){var i=n[t];this._connection.off(i)}this._systemContextsSubKey&&(this.unsubscribe(this._systemContextsSubKey),delete this._systemContextsSubKey),this._gw3Subscriptions=[],this._contextNameToId={},this._contextIdToName={},delete this._protocolVersion,this._contextsTempCache=Object.keys(this._contextNameToData).reduce((function(t,n){return t[n]=e._contextNameToData[n].context,t}),{}),this._contextNameToData={}},e.prototype.reInitiateState=function(){var e;return oi(this,void 0,void 0,(function(){var t,n,i,o,r,s,a=this;return ri(this,(function(c){switch(c.label){case 0:return this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),null===(e=this._connection.replayer)||void 0===e||e.drain(Lo.name,(function(e){var t=e.type;t&&(t===ko||t===Mo||t===Po?a.handleContextCreatedMessage(e):t===jo||t===Do||t===Wo?a.handleContextUpdatedMessage(e):t!==Oo&&t!==To||a.handleContextDestroyedMessage(e))})),[4,Promise.all(this._contextsSubscriptionsCache.map((function(e){return a.subscribe(e.contextName,e.callback,e.subKey)})))];case 1:return c.sent(),[4,this.flushQueue()];case 2:for(i in c.sent(),t=this._contextsTempCache,n=[],t)n.push(i);o=0,c.label=3;case 3:return o<n.length?(i=n[o])in t?(r=i,"object"!=typeof this._contextsTempCache[r]||0===Object.keys(this._contextsTempCache[r]).length?[3,6]:(s=this._contextsTempCache[r],this._logger.info("Re-announcing known context: ".concat(r)),[4,this.flushQueue()])):[3,6]:[3,7];case 4:return c.sent(),[4,this.update(r,s)];case 5:c.sent(),c.label=6;case 6:return o++,[3,3];case 7:return this._contextsTempCache={},this._logger.info("Contexts are re-announced"),[2]}}))}))},e.prototype.flushQueue=function(){return new Promise((function(e){return setTimeout((function(){return e()}),0)}))},e}(),Yo=function(){function e(e){this._bridge=new Xo(e)}return e.prototype.all=function(){return this._bridge.all()},e.prototype.update=function(e,t){return this.checkName(e),this.checkData(t),this._bridge.update(e,t)},e.prototype.set=function(e,t){return this.checkName(e),this.checkData(t),this._bridge.set(e,t)},e.prototype.setPath=function(e,t,n){return this.checkName(e),this.checkPath(t),""===t?(this.checkData(n),this.set(e,n)):this._bridge.setPath(e,t,n)},e.prototype.setPaths=function(e,t){if(this.checkName(e),!Array.isArray(t))throw new Error("Please provide the paths as an array of PathValues!");for(var n=0,i=t;n<i.length;n++){var o=i[n],r=o.path,s=o.value;this.checkPath(r),""===r&&this.checkData(s)}return this._bridge.setPaths(e,t)},e.prototype.subscribe=function(e,t){var n=this;if(this.checkName(e),"function"!=typeof t)throw new Error("Please provide the callback as a function!");return this._bridge.subscribe(e,(function(e,i,o,r,s){return t(e,i,o,(function(){return n._bridge.unsubscribe(r)}),s)})).then((function(e){return function(){n._bridge.unsubscribe(e)}}))},e.prototype.get=function(e){return this.checkName(e),this._bridge.get(e)},e.prototype.ready=function(){return Promise.resolve(this)},e.prototype.destroy=function(e){return this.checkName(e),this._bridge.destroy(e)},Object.defineProperty(e.prototype,"setPathSupported",{get:function(){return this._bridge.setPathSupported},enumerable:!1,configurable:!0}),e.prototype.checkName=function(e){if("string"!=typeof e||""===e)throw new Error("Please provide the name as a non-empty string!")},e.prototype.checkPath=function(e){if("string"!=typeof e)throw new Error("Please provide the path as a dot delimited string!")},e.prototype.checkData=function(e){if("object"!=typeof e)throw new Error("Please provide the data as an object!")},e}();function Zo(e,t,n){return"function"!=typeof t&&"function"!=typeof n?e:("function"!=typeof t?t=function(){}:"function"!=typeof n&&(n=function(){}),e.then(t,n))}function er(e,t,n){var i;void 0===e&&(e=0);var o=function(){i&&clearTimeout(i)};return t.then((function(){o()})).catch((function(){o()})),new Promise((function(t,o){i=setTimeout((function(){return o(n)}),e)}))}!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(Qo||(Qo={}));var tr=function(){function e(e,t,n,i){this.protocol=e,this.repo=t,this.instance=n,this.configuration=i}return e.prototype.subscribe=function(e,t,n,i,o){var r=this,s=function(e,n,i,s){var a;t.methodResponseTimeout=null!==(a=t.methodResponseTimeout)&&void 0!==a?a:t.waitTimeoutMs,r.protocol.client.subscribe(n,t,e,i,s,o)},a=new Promise((function(n,i){var o,a=function(e){n(e)},c=function(e){i(e)};if(e)if((o="string"==typeof e?{name:e}:e).name){void 0===t&&(t={});var u=t.target;if(void 0===u&&(u="best"),"string"!=typeof u||"all"===u||"best"===u){void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=t.method_response_timeout,void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=r.configuration.methodResponseTimeout)),void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=t.wait_for_method_timeout,void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=r.configuration.waitTimeoutMs));var d=0,h=r.getServerMethodsByFilterAndTarget(o,u);if(h.length>0)s(h,h[0].methods[0],a,c);else{var l=function(){if(u&&t.waitTimeoutMs)if(d+=500,(h=r.getServerMethodsByFilterAndTarget(o,u)).length>0){var n=h[0].methods[0];s(h,n,a,c)}else if(d>=t.waitTimeoutMs){s(h,"string"==typeof e?{name:e}:e,a,c)}else setTimeout(l,500)};setTimeout(l,500)}}else i(new Error('"'.concat(u,'" is not a valid target. Valid targets are "all", "best", or an instance.')))}else i("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");else i("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.")}));return Zo(a,n,i)},e.prototype.servers=function(e){var t=void 0===e?void 0:ii({},e);return this.getServers(t).map((function(e){return e.server.instance}))},e.prototype.methods=function(e){return e="string"==typeof e?{name:e}:ii({},e),this.getMethods(e)},e.prototype.methodsForInstance=function(e){return this.getMethodsForInstance(e)},e.prototype.methodAdded=function(e){return this.repo.onMethodAdded(e)},e.prototype.methodRemoved=function(e){return this.repo.onMethodRemoved(e)},e.prototype.serverAdded=function(e){return this.repo.onServerAdded(e)},e.prototype.serverRemoved=function(e){return this.repo.onServerRemoved((function(t,n){e(t,n)}))},e.prototype.serverMethodAdded=function(e){return this.repo.onServerMethodAdded((function(t,n){e({server:t,method:n})}))},e.prototype.serverMethodRemoved=function(e){return this.repo.onServerMethodRemoved((function(t,n){e({server:t,method:n})}))},e.prototype.invoke=function(e,t,n,i,o,r){return oi(this,void 0,void 0,(function(){var s,a=this;return ri(this,(function(c){return s=function(){return oi(a,void 0,void 0,(function(){var o,r,s,a,c,u,d,h,l,p,f,g,m=this;return ri(this,(function(v){switch(v.label){case 0:if(!(o="string"==typeof e?{name:e}:ii({},e)).name)return[2,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(t||(t={}),n||(n="best"),"string"==typeof n&&"all"!==n&&"best"!==n&&"skipMine"!==n)return[2,Promise.reject(new Error('"'.concat(n,'" is not a valid target. Valid targets are "all" and "best".')))];if(i||(i={}),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)),void 0!==i.waitTimeoutMs&&"number"!=typeof i.waitTimeoutMs)return[2,Promise.reject(new Error('"'.concat(i.waitTimeoutMs,'" is not a valid number for "waitTimeoutMs" ')))];if("object"!=typeof t)return[2,Promise.reject(new Error("The method arguments must be an object. method: ".concat(o.name)))];if(0!==(r=this.getServerMethodsByFilterAndTarget(o,n)).length)return[3,4];v.label=1;case 1:return v.trys.push([1,3,,4]),[4,this.tryToAwaitForMethods(o,n,i)];case 2:return r=v.sent(),[3,4];case 3:return v.sent(),s=ii(ii({},o),{getServers:function(){return[]},supportsStreaming:!1,objectTypes:null!==(p=o.objectTypes)&&void 0!==p?p:[],flags:null!==(g=null===(f=o.flags)||void 0===f?void 0:f.metadata)&&void 0!==g?g:{}}),a={method:s,called_with:t,message:"Can not find a method matching ".concat(JSON.stringify(e)," with server filter ").concat(JSON.stringify(n)),executed_by:void 0,returned:void 0,status:void 0},[2,Promise.reject(a)];case 4:return c=i.methodResponseTimeoutMs,u=i,d=r.map((function(e){var n=go(),i=e.methods[0],o=e.server,r=m.protocol.client.invoke(n,i,t,o,u);return Promise.race([r,er(c,r,{invocationId:n,message:"Invocation timeout (".concat(c," ms) reached for method name: ").concat(null==i?void 0:i.name,", target instance: ").concat(JSON.stringify(o.instance),", options: ").concat(JSON.stringify(u)),status:Qo.Error})])})),[4,Promise.all(d)];case 5:return h=v.sent(),l=this.getInvocationResultObj(h,o,t),h.every((function(e){return e.status===Qo.Error}))?[2,Promise.reject(l)]:[2,l]}}))}))},[2,Zo(s(),o,r)]}))}))},e.prototype.getInvocationResultObj=function(e,t,n){var i=e.filter((function(e){return e.status===Qo.Success})).reduce((function(e,i){return e=si(si([],e,!0),[{executed_by:i.instance,returned:i.result,called_with:n,method:t,message:i.message,status:i.status}],!1)}),[]),o=e.filter((function(e){return e.status===Qo.Error})).reduce((function(e,i){return e=si(si([],e,!0),[{executed_by:i.instance,called_with:n,name:t.name,message:i.message}],!1)}),[]),r=e[0];return{method:t,called_with:n,returned:r.result,executed_by:r.instance,all_return_values:i,all_errors:o,message:r.message,status:r.status}},e.prototype.tryToAwaitForMethods=function(e,t,n){var i=this;return new Promise((function(o,r){if(0!==n.waitTimeoutMs)var s=0,a=setInterval((function(){s+=500;var c=i.getServerMethodsByFilterAndTarget(e,t);if(c.length>0)clearInterval(a),o(c);else if(s>=(n.waitTimeoutMs||1e4))return clearInterval(a),void r()}),500);else r()}))},e.prototype.filterByTarget=function(e,t){var n=this;if("string"!=typeof e){return(Array.isArray(e)?e:[e]).reduce((function(e,i){var o=t.filter((function(e){return n.instanceMatch(i,e.server.instance)}));return e.concat(o)}),[])}if("all"===e)return si([],t,!0);if("best"===e){var i=t.find((function(e){return e.server.instance.isLocal}));if(i)return[i];if(void 0!==t[0])return[t[0]]}else if("skipMine"===e)return t.filter((function(e){return e.server.instance.peerId!==n.instance.peerId}));return[]},e.prototype.instanceMatch=function(e,t){return this.containsProps(e,t)},e.prototype.methodMatch=function(e,t){return this.containsProps(e,t)},e.prototype.containsProps=function(e,t){return Object.keys(e).filter((function(t){return 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((function(n){var i,o=e[n],r=t[n];switch(n){case"objectTypes":i=(o||[]).every((function(e){return(r||[]).includes(e)}));break;case"flags":i=Vo(r||{},o||{});break;default:i=String(o).toLowerCase()===String(r).toLowerCase()}return i}))},e.prototype.getMethods=function(e){var t=this;return void 0===e?this.repo.getMethods():this.repo.getMethods().filter((function(n){return t.methodMatch(e,n)}))},e.prototype.getMethodsForInstance=function(e){var t=this,n=this.repo.getServers().filter((function(n){return t.instanceMatch(e,n.instance)}));if(0===n.length)return[];var i={};return 1===n.length?i=n[0].methods:n.forEach((function(e){Object.keys(e.methods).forEach((function(t){var n=e.methods[t];i[n.identifier]=n}))})),Object.keys(i).map((function(e){return i[e]}))},e.prototype.getServers=function(e){var t=this,n=this.repo.getServers();return void 0===e?n.map((function(e){return{server:e,methods:[]}})):n.reduce((function(n,i){var o=Object.values(i.methods).filter((function(n){return t.methodMatch(e,n)}));return o.length>0&&n.push({server:i,methods:o}),n}),[])},e.prototype.getServerMethodsByFilterAndTarget=function(e,t){var n=this.getServers(e);return this.filterByTarget(t,n)},e}(),nr=function(){function e(e,t,n){this.protocol=e,this.repoMethod=t,this.subscription=n}return Object.defineProperty(e.prototype,"stream",{get:function(){if(!this.repoMethod.stream)throw new Error("no stream");return this.repoMethod.stream},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"arguments",{get:function(){return this.subscription.arguments||{}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"branchKey",{get:function(){return this.subscription.branchKey},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"instance",{get:function(){if(!this.subscription.instance)throw new Error("no instance");return this.subscription.instance},enumerable:!1,configurable:!0}),e.prototype.close=function(){this.protocol.server.closeSingleSubscription(this.repoMethod,this.subscription)},e.prototype.push=function(e){this.protocol.server.pushDataToSingle(this.repoMethod,this.subscription,e)},e}(),ir=function(){function e(e,t,n){this.protocol=e,this.repoMethod=t,this.requestContext=n,this.arguments=n.arguments,this.instance=n.instance}return e.prototype.accept=function(){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,"")},e.prototype.acceptOnBranch=function(e){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,e)},e.prototype.reject=function(e){this.protocol.server.rejectRequest(this.requestContext,this.repoMethod,e)},e}(),or=function(){function e(e,t){var n=this;this.protocol=e,this.server=t,e.server.onSubRequest((function(e,t){return n.handleSubRequest(e,t)})),e.server.onSubAdded((function(e,t){return n.handleSubAdded(e,t)})),e.server.onSubRemoved((function(e,t){return n.handleSubRemoved(e,t)}))}return e.prototype.handleSubRequest=function(e,t){if(t&&t.streamCallbacks&&"function"==typeof t.streamCallbacks.subscriptionRequestHandler){var n=new ir(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(n)}},e.prototype.handleSubAdded=function(e,t){if(t&&t.streamCallbacks&&"function"==typeof t.streamCallbacks.subscriptionAddedHandler){var n=new nr(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(n)}},e.prototype.handleSubRemoved=function(e,t){if(t&&t.streamCallbacks&&"function"==typeof t.streamCallbacks.subscriptionRemovedHandler){var n=new nr(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(n)}},e}(),rr=function(){function e(e,t,n){this.key=e,this.protocol=t,this.repoMethod=n}return e.prototype.subscriptions=function(){var e=this;return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map((function(t){return new nr(e.protocol,e.repoMethod,t)}))},e.prototype.close=function(){this.protocol.server.closeAllSubscriptions(this.repoMethod,this.key)},e.prototype.push=function(e){this.protocol.server.pushData(this.repoMethod,e,[this.key])},e}(),sr=function(){function e(e,t,n){this._protocol=e,this._repoMethod=t,this._server=n,this.name=this._repoMethod.definition.name}return e.prototype.branches=function(e){var t=this,n=this._protocol.server.getBranchList(this._repoMethod);return e?n.indexOf(e)>-1?new rr(e,this._protocol,this._repoMethod):void 0:n.map((function(e){return new rr(e,t._protocol,t._repoMethod)}))},e.prototype.branch=function(e){return this.branches(e)},e.prototype.subscriptions=function(){var e=this;return this._protocol.server.getSubscriptionList(this._repoMethod).map((function(t){return new nr(e._protocol,e._repoMethod,t)}))},Object.defineProperty(e.prototype,"definition",{get:function(){var e,t=this._repoMethod.definition;return{accepts:t.accepts,description:t.description,displayName:t.displayName,name:t.name,objectTypes:t.objectTypes,returns:t.returns,supportsStreaming:t.supportsStreaming,flags:null===(e=t.flags)||void 0===e?void 0:e.metadata}},enumerable:!1,configurable:!0}),e.prototype.close=function(){this._protocol.server.closeAllSubscriptions(this._repoMethod),this._server.unregister(this._repoMethod.definition,!0)},e.prototype.push=function(e,t){if("string"!=typeof t&&!Array.isArray(t)&&void 0!==t)throw new Error("invalid branches should be string or string array");if("object"!=typeof e)throw new Error("Invalid arguments. Data must be an object.");this._protocol.server.pushData(this._repoMethod,e,t)},e.prototype.updateRepoMethod=function(e){this._repoMethod=e},e}(),ar=function(){function e(e,t){this.protocol=e,this.serverRepository=t,this.invocations=0,this.currentlyUnregistering={},this.streaming=new or(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}return e.prototype.createStream=function(e,t,n,i,o){var r=this,s=new Promise((function(n,i){if(e){var s;if(!(s="string"==typeof e?{name:""+e}:ii({},e)).name)return i("The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ".concat(JSON.stringify(s)));if(r.serverRepository.getList().some((function(e){return e.definition.name===s.name})))return i('A stream with the name "'.concat(s.name,'" already exists! Please, provide a unique name for the stream.'));s.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=function(e){e.accept()});var a=r.serverRepository.add({definition:s,streamCallbacks:t,protocolState:{}});r.protocol.server.createStream(a).then((function(){var e;o?(e=o,o.updateRepoMethod(a)):e=new sr(r.protocol,a,r),a.stream=e,n(e)})).catch((function(e){a.repoId&&r.serverRepository.remove(a.repoId),i(e)}))}else 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.")}));return Zo(s,n,i)},e.prototype.register=function(e,t){var n=this;if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject("The second parameter must be a callback function. Method: ".concat("string"==typeof e?e:e.name));var i=function(e,i){return oi(n,void 0,void 0,(function(){var n,o,r;return ri(this,(function(s){switch(s.label){case 0:return s.trys.push([0,4,,5]),(n=t(e.args,e.instance))&&"function"==typeof n.then?[4,n]:[3,2];case 1:return o=s.sent(),i(void 0,o),[3,3];case 2:i(void 0,n),s.label=3;case 3:return[3,5];case 4:return r=s.sent(),i(null!=r?r:"",null!=r?r:""),[3,5];case 5:return[2]}}))}))};return i.userCallback=t,this.registerCore(e,i)},e.prototype.registerAsync=function(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject("The second parameter must be a callback function. Method: ".concat("string"==typeof e?e:e.name));var n=function(e,n){try{var i=!1,o=function(e){i||n(void 0,e),i=!0},r=function(e){i||(e||(e=""),n(e,e)),i=!0},s=t(e.args,e.instance,o,r);s&&"function"==typeof s.then&&s.then(o).catch(r)}catch(e){n(e,void 0)}};return n.userCallbackAsync=t,this.registerCore(e,n)},e.prototype.unregister=function(e,t){return void 0===t&&(t=!1),oi(this,void 0,void 0,(function(){var n,i;return ri(this,(function(o){switch(o.label){case 0:return void 0===e?[2,Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.")]:"function"!=typeof e?[3,2]:[4,this.unregisterWithPredicate(e,t)];case 1:case 3:return o.sent(),[2];case 2:return void 0===(n="string"==typeof e?{name:e}:e).name?[2,Promise.reject("Method name is required. Cannot find a method if the method name is undefined!")]:(i=this.serverRepository.getList().find((function(e){return e.definition.name===n.name&&(e.definition.supportsStreaming||!1)===t})))?[4,this.removeMethodsOrStreams([i])]:[2,Promise.reject('Method with a name "'.concat(n.name,'" does not exist or is not registered by your application!'))]}}))}))},e.prototype.unregisterWithPredicate=function(e,t){return oi(this,void 0,void 0,(function(){var n;return ri(this,(function(i){switch(i.label){case 0:return(n=this.serverRepository.getList().filter((function(t){return e(t.definition)})).filter((function(e){return(e.definition.supportsStreaming||!1)===t})))&&0!==n.length?[4,this.removeMethodsOrStreams(n)]:[2,Promise.reject("Could not find a ".concat(t?"stream":"method"," matching the specified condition!"))];case 1:return i.sent(),[2]}}))}))},e.prototype.removeMethodsOrStreams=function(e){var t=this,n=[];return e.forEach((function(e){var i=t.protocol.server.unregister(e).then((function(){e.repoId&&t.serverRepository.remove(e.repoId)}));n.push(i),t.addAsCurrentlyUnregistering(e.definition.name,i)})),Promise.all(n)},e.prototype.addAsCurrentlyUnregistering=function(e,t){return oi(this,void 0,void 0,(function(){var n,i=this;return ri(this,(function(o){return n=new Promise((function(e){return setTimeout(e,5e3)})),this.currentlyUnregistering[e]=Promise.race([t,n]).then((function(){delete i.currentlyUnregistering[e]})),[2]}))}))},e.prototype.registerCore=function(e,t){return oi(this,void 0,void 0,(function(){var n,i,o,r=this;return ri(this,(function(s){switch(s.label){case 0:return(n="string"==typeof e?{name:""+e}:ii({},e)).name?(i=this.currentlyUnregistering[n.name])?[4,i]:[3,2]:[2,Promise.reject("Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ".concat(JSON.stringify(e)))];case 1:s.sent(),s.label=2;case 2:return this.serverRepository.getList().some((function(e){return e.definition.name===n.name}))?[2,Promise.reject('A method with the name "'.concat(n.name,'" already exists! Please, provide a unique name for the method.'))]:n.supportsStreaming?[2,Promise.reject("When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “".concat(n.name,"” to be a stream, please use the “glue.interop.createStream()” method."))]:(o=this.serverRepository.add({definition:n,theFunction:t,protocolState:{}}),[2,this.protocol.server.register(o).catch((function(e){throw(null==o?void 0:o.repoId)&&r.serverRepository.remove(o.repoId),e}))])}}))}))},e.prototype.onMethodInvoked=function(e,t,n){var i=this;e&&e.theFunction&&e.theFunction(n,(function(n,o){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: ".concat(Object.keys(n))}o?("object"!=typeof o||Array.isArray(o))&&(o={_value:o}):o={},i.protocol.server.methodInvocationResult(e,t,n,o)}))},e}(),cr=function(){function e(e,t,n){var i=this;this.wrapped={},this.wrapped.getMethods=function(){return e.methodsForInstance(this)},this.wrapped.getStreams=function(){return e.methodsForInstance(this).filter((function(e){return e.supportsStreaming}))},t&&this.refreshWrappedObject(t),n&&(n.loggedIn((function(){i.refresh(n)})),this.refresh(n))}return e.prototype.unwrap=function(){return this.wrapped},e.prototype.refresh=function(e){if(e){var t=null==e?void 0:e.resolvedIdentity,n=Object.assign({},null!=t?t:{},{peerId:null==e?void 0:e.peerId});this.refreshWrappedObject(n)}},e.prototype.refreshWrappedObject=function(e){var t,n,i,o,r=this;Object.keys(e).forEach((function(t){r.wrapped[t]=e[t]})),this.wrapped.user=e.user,this.wrapped.instance=e.instance,this.wrapped.application=null!==(t=e.application)&&void 0!==t?t:go(),this.wrapped.applicationName=e.applicationName,this.wrapped.pid=null!==(i=null!==(n=e.pid)&&void 0!==n?n:e.process)&&void 0!==i?i: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=null===(o=e.isLocal)||void 0===o||o,this.wrapped.api=e.api,this.wrapped.service=e.service,this.wrapped.peerId=e.peerId},e}(),ur=function(e){return ii(ii({},e),{flags:e.flags.metadata||{}})},dr=function(){function e(e,t){this.logger=e,this.API=t,this.servers={},this.methodsCount={},this.callbacks=ji();var n=this.API.instance.peerId;this.myServer={id:n,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[n]=this.myServer}return e.prototype.addServer=function(e,t){this.logger.debug("adding server ".concat(t));var n=this.servers[t];if(n)return n.id;var i=new cr(this.API,e),o={id:t,methods:{},instance:i.unwrap(),wrapper:i};return this.servers[t]=o,this.callbacks.execute("onServerAdded",o.instance),t},e.prototype.removeServerById=function(e,t){var n=this,i=this.servers[e];i?(this.logger.debug("removing server ".concat(e)),Object.keys(i.methods).forEach((function(t){n.removeServerMethod(e,t)})),delete this.servers[e],this.callbacks.execute("onServerRemoved",i.instance,t)):this.logger.warn("not aware of server ".concat(e,", my state ").concat(JSON.stringify(Object.keys(this.servers))))},e.prototype.addServerMethod=function(e,t){var n,i=this.servers[e];if(!i)throw new Error("server does not exists");if(!i.methods[t.id]){var o=this.createMethodIdentifier(t),r=this,s={identifier:o,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:null!==(n=t.flags)&&void 0!==n?n:{},getServers:function(){return r.getServersByMethod(o)}};s.object_types=s.objectTypes,s.display_name=s.displayName,s.version=s.version,i.methods[t.id]=s;var a=ur(s);return this.methodsCount[o]||(this.methodsCount[o]=0,this.callbacks.execute("onMethodAdded",a)),this.methodsCount[o]=this.methodsCount[o]+1,this.callbacks.execute("onServerMethodAdded",i.instance,a),s}},e.prototype.removeServerMethod=function(e,t){var n=this.servers[e];if(!n)throw new Error("server does not exists");var i=n.methods[t];delete n.methods[t];var o=ur(i);this.methodsCount[i.identifier]=this.methodsCount[i.identifier]-1,0===this.methodsCount[i.identifier]&&this.callbacks.execute("onMethodRemoved",o),this.callbacks.execute("onServerMethodRemoved",n.instance,o)},e.prototype.getMethods=function(){return this.extractMethodsFromServers(Object.values(this.servers)).map(ur)},e.prototype.getServers=function(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)},e.prototype.onServerAdded=function(e){var t=this.callbacks.add("onServerAdded",e),n=this.getServers().map((function(e){return e.instance}));return this.returnUnsubWithDelayedReplay(t,n,e)},e.prototype.onMethodAdded=function(e){var t=this.callbacks.add("onMethodAdded",e),n=this.getMethods();return this.returnUnsubWithDelayedReplay(t,n,e)},e.prototype.onServerMethodAdded=function(e){var t=this.callbacks.add("onServerMethodAdded",e),n=!1,i=this.getServers();return setTimeout((function(){i.forEach((function(t){var i=t.methods;Object.keys(i).forEach((function(o){n||e(t.instance,i[o])}))}))}),0),function(){n=!0,t()}},e.prototype.onMethodRemoved=function(e){return this.callbacks.add("onMethodRemoved",e)},e.prototype.onServerRemoved=function(e){return this.callbacks.add("onServerRemoved",e)},e.prototype.onServerMethodRemoved=function(e){return this.callbacks.add("onServerMethodRemoved",e)},e.prototype.getServerById=function(e){return this.hideServerMethodSystemFlags(this.servers[e])},e.prototype.reset=function(){var e,t=this;Object.keys(this.servers).forEach((function(e){t.removeServerById(e,"reset")})),this.servers=((e={})[this.myServer.id]=this.myServer,e),this.methodsCount={}},e.prototype.createMethodIdentifier=function(e){var t,n,i=null!==(t=e.input_signature)&&void 0!==t?t:"",o=null!==(n=e.result_signature)&&void 0!==n?n:"";return(e.name+i+o).toLowerCase()},e.prototype.getServersByMethod=function(e){var t=[];return Object.values(this.servers).forEach((function(n){Object.values(n.methods).forEach((function(i){i.identifier===e&&t.push(n.instance)}))})),t},e.prototype.returnUnsubWithDelayedReplay=function(e,t,n){var i=!1;return setTimeout((function(){t.forEach((function(e){i||n(e)}))}),0),function(){i=!0,e()}},e.prototype.hideServerMethodSystemFlags=function(e){var t={};return Object.entries(e.methods).forEach((function(e){var n=e[0],i=e[1];t[n]=ur(i)})),ii(ii({},e),{methods:t})},e.prototype.extractMethodsFromServers=function(e){return Object.values(e).reduce((function(e,t){return si(si([],e,!0),Object.values(t.methods),!0)}),[])},e}(),hr=function(){function e(){this.nextId=0,this.methods=[]}return e.prototype.add=function(e){return e.repoId=String(this.nextId),this.nextId+=1,this.methods.push(e),e},e.prototype.remove=function(e){if("string"!=typeof e)return new TypeError("Expecting a string");this.methods=this.methods.filter((function(t){return t.repoId!==e}))},e.prototype.getById=function(e){if("string"==typeof e)return this.methods.find((function(t){return t.repoId===e}))},e.prototype.getList=function(){return this.methods.map((function(e){return e}))},e.prototype.length=function(){return this.methods.length},e.prototype.reset=function(){this.methods=[]},e}(),lr="onSubscriptionRequest",pr="onSubscriptionAdded",fr="onSubscriptionRemoved",gr=function(){function e(e,t,n){var i=this;this.session=e,this.repository=t,this.serverRepository=n,this.ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure",this.callbacks=ji(),this.nextStreamId=0,e.on("add-interest",(function(e){i.handleAddInterest(e)})),e.on("remove-interest",(function(e){i.handleRemoveInterest(e)}))}return e.prototype.acceptRequestOnBranch=function(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.");var i=this.getStreamId(t,n),o=e.msg.subscription_id,r={id:o,arguments:e.arguments,instance:e.instance,branchKey:n,streamId:i,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[o]=r,this.session.sendFireAndForget({type:"accepted",subscription_id:o,stream_id:i}),this.callbacks.execute(pr,r,t)},e.prototype.rejectRequest=function(e,t,n){"string"!=typeof n&&(n=""),this.sendSubscriptionFailed("Subscription rejected by user. "+n,e.msg.subscription_id)},e.prototype.pushData=function(e,t,n){var i=this;if("object"==typeof e&&Array.isArray(e.protocolState.branchKeyToStreamIdMap)){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((function(e){return!n||0===n.length||n.indexOf(e.key)>=0})).map((function(e){return e.streamId})).forEach((function(e){var n={type:"publish",stream_id:e,data:t};i.session.sendFireAndForget(n)}))}},e.prototype.pushDataToSingle=function(e,t,n){if("object"!=typeof n)throw new Error("Invalid arguments. Data must be an object.");var i={type:"post",subscription_id:t.id,data:n};this.session.sendFireAndForget(i)},e.prototype.closeSingleSubscription=function(e,t){e.protocolState.subscriptionsMap&&delete e.protocolState.subscriptionsMap[t.id];var n={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(n),t.instance,this.callbacks.execute(fr,t,e)},e.prototype.closeMultipleSubscriptions=function(e,t){var n=this;if("object"==typeof e&&"object"==typeof e.protocolState.subscriptionsMap&&e.protocolState.subscriptionsMap){var i=e.protocolState.subscriptionsMap,o=Object.keys(i).map((function(e){return i[e]}));"string"==typeof t&&(o=o.filter((function(e){return e.branchKey===t}))),o.forEach((function(e){delete i[e.id];var t={type:"drop-subscription",subscription_id:e.id,reason:"Server dropping all subscriptions on stream_id: "+e.streamId};n.session.sendFireAndForget(t)}))}},e.prototype.getSubscriptionList=function(e,t){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];var n=e.protocolState.subscriptionsMap,i=Object.keys(n).map((function(e){return n[e]}));return"string"!=typeof t?i:i.filter((function(e){return e.branchKey===t}))},e.prototype.getBranchList=function(e){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];var t=e.protocolState.subscriptionsMap,n=Object.keys(t).map((function(e){return t[e]})),i=[];return n.forEach((function(e){var t="";"object"==typeof e&&"string"==typeof e.branchKey&&(t=e.branchKey),-1===i.indexOf(t)&&i.push(t)})),i},e.prototype.onSubAdded=function(e){this.onSubscriptionLifetimeEvent(pr,e)},e.prototype.onSubRequest=function(e){this.onSubscriptionLifetimeEvent(lr,e)},e.prototype.onSubRemoved=function(e){this.onSubscriptionLifetimeEvent(fr,e)},e.prototype.handleRemoveInterest=function(e){var t=this.serverRepository.getById(e.method_id);if("string"==typeof e.subscription_id&&"object"==typeof t&&t.protocolState.subscriptionsMap&&"object"==typeof t.protocolState.subscriptionsMap[e.subscription_id]){var n=t.protocolState.subscriptionsMap[e.subscription_id];delete t.protocolState.subscriptionsMap[e.subscription_id],this.callbacks.execute(fr,n,t)}},e.prototype.onSubscriptionLifetimeEvent=function(e,t){this.callbacks.add(e,t)},e.prototype.getNextStreamId=function(){return this.nextStreamId+++""},e.prototype.handleAddInterest=function(e){var t=this.repository.getServerById(e.caller_id).instance,n={msg:e,arguments:e.arguments_kv||{},instance:t},i=this.serverRepository.getById(e.method_id);if(void 0!==i)i.protocolState.subscriptionsMap&&i.protocolState.subscriptionsMap[e.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+e.subscription_id+" already exists.",e.subscription_id):this.callbacks.execute(lr,n,i);else{var o="No method with id "+e.method_id+" on this server.";this.sendSubscriptionFailed(o,e.subscription_id)}},e.prototype.sendSubscriptionFailed=function(e,t){var n={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:e,request_id:t};this.session.sendFireAndForget(n)},e.prototype.getStreamId=function(e,t){if("string"!=typeof t&&(t=""),!e.protocolState.branchKeyToStreamIdMap)throw new Error("streaming ".concat(e.definition.name," method without protocol state"));var n=e.protocolState.branchKeyToStreamIdMap.filter((function(e){return e.key===t}))[0],i=n?n.streamId:void 0;return"string"==typeof i&&""!==i||(i=this.getNextStreamId(),e.protocolState.branchKeyToStreamIdMap.push({key:t,streamId:i})),i},e}(),mr=function(){function e(e,t,n,i){var o=this;this.session=e,this.clientRepository=t,this.serverRepository=n,this.logger=i,this.callbacks=ji(),this.streaming=new gr(e,t,n),this.session.on("invoke",(function(e){return o.handleInvokeMessage(e)}))}return e.prototype.createStream=function(e){return e.protocolState.subscriptionsMap={},e.protocolState.branchKeyToStreamIdMap=[],this.register(e,!0)},e.prototype.register=function(e,t){var n,i=this,o=e.definition,r=Object.assign({},{metadata:null!==(n=o.flags)&&void 0!==n?n:{}},{streaming:t||!1}),s={type:"register",methods:[{id:e.repoId,name:o.name,display_name:o.displayName,description:o.description,version:o.version,flags:r,object_types:o.objectTypes||o.object_types,input_signature:o.accepts,result_signature:o.returns,restrictions:void 0}]};return this.session.send(s,{methodId:e.repoId}).then((function(){i.logger.debug("registered method "+e.definition.name+" with id "+e.repoId)})).catch((function(t){throw i.logger.warn("failed to register method ".concat(e.definition.name," with id ").concat(e.repoId," - ").concat(JSON.stringify(t))),t}))},e.prototype.onInvoked=function(e){this.callbacks.add("onInvoked",e)},e.prototype.methodInvocationResult=function(e,t,n,i){var o;o=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(o)},e.prototype.unregister=function(e){return oi(this,void 0,void 0,(function(){var t;return ri(this,(function(n){switch(n.label){case 0:return t={type:"unregister",methods:[e.repoId]},[4,this.session.send(t)];case 1:return n.sent(),[2]}}))}))},e.prototype.getBranchList=function(e){return this.streaming.getBranchList(e)},e.prototype.getSubscriptionList=function(e,t){return this.streaming.getSubscriptionList(e,t)},e.prototype.closeAllSubscriptions=function(e,t){this.streaming.closeMultipleSubscriptions(e,t)},e.prototype.pushData=function(e,t,n){this.streaming.pushData(e,t,n)},e.prototype.pushDataToSingle=function(e,t,n){this.streaming.pushDataToSingle(e,t,n)},e.prototype.closeSingleSubscription=function(e,t){this.streaming.closeSingleSubscription(e,t)},e.prototype.acceptRequestOnBranch=function(e,t,n){this.streaming.acceptRequestOnBranch(e,t,n)},e.prototype.rejectRequest=function(e,t,n){this.streaming.rejectRequest(e,t,n)},e.prototype.onSubRequest=function(e){this.streaming.onSubRequest(e)},e.prototype.onSubAdded=function(e){this.streaming.onSubAdded(e)},e.prototype.onSubRemoved=function(e){this.streaming.onSubRemoved(e)},e.prototype.handleInvokeMessage=function(e){var t=e.invocation_id,n=e.caller_id,i=e.method_id,o=e.arguments_kv,r=this.serverRepository.getList().filter((function(e){return e.repoId===i}))[0];if(void 0!==r){var s={args:o,instance:this.clientRepository.getServerById(n).instance};this.callbacks.execute("onInvoked",r,t,s)}},e}(),vr=function(){function e(e,t){this.repository=e,this.subscriptionData=t}return Object.defineProperty(e.prototype,"requestArguments",{get:function(){return this.subscriptionData.params.arguments||{}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"servers",{get:function(){var e=this;return this.subscriptionData.trackedServers.filter((function(e){return e.subscriptionId})).map((function(t){return e.repository.getServerById(t.serverId).instance}))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"serverInstance",{get:function(){return this.servers[0]},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stream",{get:function(){return this.subscriptionData.method},enumerable:!1,configurable:!0}),e.prototype.onData=function(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((function(t){e(t)}))},e.prototype.onClosed=function(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onClosed.push(e)},e.prototype.onFailed=function(e){},e.prototype.onConnected=function(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onConnected.push(e)},e.prototype.close=function(){this.subscriptionData.close()},e.prototype.setNewSubscription=function(e){this.subscriptionData=e},e}(),yr=function(){function e(e){this.config=e,this.cache=[],this.timeoutIds=[]}return e.prototype.add=function(e){var t=this,n=go();this.cache.push({id:n,element:e});var i=setTimeout((function(){var e=t.cache.findIndex((function(e){return e.id===n}));e<0||t.cache.splice(e,1)}),this.config.ELEMENT_TTL_MS);this.timeoutIds.push(i)},e.prototype.flush=function(){var e=this.cache.map((function(e){return e.element}));return this.timeoutIds.forEach((function(e){return clearInterval(e)})),this.cache=[],this.timeoutIds=[],e},e}(),br="awaitingAccept",wr="subscribed",Ir="Subscription failed.",Cr="Subscription rejected.",Sr="ClientInitiated",xr=function(){function e(e,t,n){var i=this;this.session=e,this.repository=t,this.logger=n,this.subscriptionsList={},this.timedCache=new yr({ELEMENT_TTL_MS:1e4}),this.subscriptionIdToLocalKeyMap={},this.nextSubLocalKey=0,this.handleErrorSubscribing=function(e){var t=e._tag,n=t.subLocalKey,o=i.subscriptionsList[n];if("object"==typeof o&&(o.trackedServers=o.trackedServers.filter((function(e){return e.serverId!==t.serverId})),o.trackedServers.length<=0)){if(clearTimeout(o.timeoutId),o.status===br){var r="string"==typeof e.reason&&""!==e.reason?' Publisher said "'+e.reason+'".':" No reason given.",s="object"==typeof o.params.arguments?JSON.stringify(o.params.arguments):"{}";o.error({message:Cr+r+" Called with:"+s,called_with:o.params.arguments,method:o.method})}else o.status===wr&&i.callOnClosedHandlers(o);delete i.subscriptionsList[n]}},this.handleSubscribed=function(e){var t=e._tag.subLocalKey,n=i.subscriptionsList[t];if("object"==typeof n){var o=e._tag.serverId,r=n.trackedServers.filter((function(e){return e.serverId===o}))[0];if("object"==typeof r){r.subscriptionId=e.subscription_id,i.subscriptionIdToLocalKeyMap[e.subscription_id]=t;var s=n.status===br;if(n.status=wr,s){var a=!1,c=n.subscription;c?(c.setNewSubscription(n),n.success(c),a=!0):(c=new vr(i.repository,n),n.subscription=c,n.success(c));for(var u=0,d=n.handlers.onConnected;u<d.length;u++){var h=d[u];try{h(c.serverInstance,a)}catch(e){}}}}}},this.handleEventData=function(e){var t=i.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0!==t){var n=i.subscriptionsList[t];if("object"==typeof n){var o=n.trackedServers.filter((function(t){return t.subscriptionId===e.subscription_id}));if(1===o.length){var r=e.oob,s=o[0].serverId,a=function(){return{data:e.data,server:i.repository.getServerById(s).instance,requestArguments:n.params.arguments,message:void 0,private:r}},c=n.handlers.onData,u=n.queued.data;c.length>0?c.forEach((function(e){"function"==typeof e&&e(a())})):u.push(a())}}}},this.handleSubscriptionCancelled=function(e){var t=i.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0!==t){var n=i.subscriptionsList[t];if("object"==typeof n){var o=n.trackedServers.length-1;n.trackedServers=n.trackedServers.filter((function(t){return t.subscriptionId!==e.subscription_id||(n.queued.closers.push(t.serverId),!1)})),n.trackedServers.length===o&&(n.trackedServers.length<=0&&(i.timedCache.add(n),clearTimeout(n.timeoutId),i.callOnClosedHandlers(n),delete i.subscriptionsList[t]),delete i.subscriptionIdToLocalKeyMap[e.subscription_id])}}},e.on("subscribed",this.handleSubscribed),e.on("event",this.handleEventData),e.on("subscription-cancelled",this.handleSubscriptionCancelled)}return e.prototype.subscribe=function(e,t,n,i,o,r){var s=this;if(0!==n.length){var a=this.getNextSubscriptionLocalKey(),c=this.registerSubscription(a,e,t,i,o,t.methodResponseTimeout||1e4,r);"object"==typeof c?n.forEach((function(n){var i=n.server.id,o=n.methods.find((function(t){return t.name===e.name}));if(o){c.trackedServers.push({serverId:i,subscriptionId:void 0});var r={type:"subscribe",server_id:i,method_id:o.gatewayId,arguments_kv:t.arguments};s.session.send(r,{serverId:i,subLocalKey:a}).then((function(e){return s.handleSubscribed(e)})).catch((function(e){return s.handleErrorSubscribing(e)}))}else s.logger.error("can not find method ".concat(e.name," for target ").concat(n.server.id))})):o({method:e,called_with:t.arguments,message:Ir+" Unable to register the user callbacks."})}else o({method:e,called_with:t.arguments,message:Ir+" No available servers matched the target params."})},e.prototype.drainSubscriptions=function(){var e=Object.values(this.subscriptionsList);return this.subscriptionsList={},this.subscriptionIdToLocalKeyMap={},e},e.prototype.drainSubscriptionsCache=function(){return this.timedCache.flush()},e.prototype.getNextSubscriptionLocalKey=function(){var e=this.nextSubLocalKey;return this.nextSubLocalKey+=1,e},e.prototype.registerSubscription=function(e,t,n,i,o,r,s){var a=this,c={localKey:e,status:br,method:t,params:n,success:i,error:o,trackedServers:[],handlers:{onData:(null==s?void 0:s.handlers.onData)||[],onClosed:(null==s?void 0:s.handlers.onClosed)||[],onConnected:(null==s?void 0:s.handlers.onConnected)||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:function(){return a.closeSubscription(e)},subscription:null==s?void 0:s.subscription};return s||(n.onData&&c.handlers.onData.push(n.onData),n.onClosed&&c.handlers.onClosed.push(n.onClosed),n.onConnected&&c.handlers.onConnected.push(n.onConnected)),this.subscriptionsList[e]=c,c.timeoutId=setTimeout((function(){if(void 0!==a.subscriptionsList[e]){var i=a.subscriptionsList[e];i.status===br?(o({method:t,called_with:n.arguments,message:Ir+" Subscription attempt timed out after "+r+" ms."}),delete a.subscriptionsList[e]):i.status===wr&&i.trackedServers.length>0&&(i.trackedServers=i.trackedServers.filter((function(e){return void 0!==e.subscriptionId})),delete i.timeoutId,i.trackedServers.length<=0&&(a.callOnClosedHandlers(i),delete a.subscriptionsList[e]))}}),r),c},e.prototype.callOnClosedHandlers=function(e,t){var n,i=e.queued.closers.length,o=i>0?e.queued.closers[i-1]:null;void 0!==o&&"string"==typeof o&&(n=this.repository.getServerById(o).instance),e.handlers.onClosed.forEach((function(i){"function"==typeof i&&i({message:t||"ServerInitiated",requestArguments:e.params.arguments||{},server:n,stream:e.method})}))},e.prototype.closeSubscription=function(e){var t=this,n=this.subscriptionsList[e];"object"==typeof n&&(n.trackedServers.forEach((function(e){void 0!==e.subscriptionId&&(n.queued.closers.push(e.serverId),t.session.sendFireAndForget({type:"unsubscribe",subscription_id:e.subscriptionId,reason_uri:"",reason:Sr}),delete t.subscriptionIdToLocalKeyMap[e.subscriptionId])})),n.trackedServers=[],this.callOnClosedHandlers(n,Sr),delete this.subscriptionsList[e])},e}(),_r=function(){function e(e,t,n){var i=this;this.session=e,this.repository=t,this.logger=n,e.on("peer-added",(function(e){return i.handlePeerAdded(e)})),e.on("peer-removed",(function(e){return i.handlePeerRemoved(e)})),e.on("methods-added",(function(e){return i.handleMethodsAddedMessage(e)})),e.on("methods-removed",(function(e){return i.handleMethodsRemovedMessage(e)})),this.streaming=new xr(e,t,n)}return e.prototype.subscribe=function(e,t,n,i,o,r){this.streaming.subscribe(e,t,n,i,o,r)},e.prototype.invoke=function(e,t,n,i){var o=this,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((function(e){return o.handleResultMessage(e)})).catch((function(e){return o.handleInvocationError(e)}))},e.prototype.drainSubscriptions=function(){return this.streaming.drainSubscriptions()},e.prototype.drainSubscriptionsCache=function(){return this.streaming.drainSubscriptionsCache()},e.prototype.handlePeerAdded=function(e){var t=e.new_peer_id,n=e.identity,i=!e.meta||e.meta.local,o=Number(n.process),r={machine:n.machine,pid:isNaN(o)?n.process:o,instance:n.instance,application:n.application,applicationName:n.applicationName,environment:n.environment,region:n.region,user:n.user,windowId:n.windowId,peerId:t,api:n.api,isLocal:i};this.repository.addServer(r,t)},e.prototype.handlePeerRemoved=function(e){var t=e.removed_id,n=e.reason;this.repository.removeServerById(t,n)},e.prototype.handleMethodsAddedMessage=function(e){var t=this,n=e.server_id;e.methods.forEach((function(e){t.repository.addServerMethod(n,e)}))},e.prototype.handleMethodsRemovedMessage=function(e){var t=this,n=e.server_id,i=e.methods,o=this.repository.getServerById(n);Object.keys(o.methods).forEach((function(e){var r=o.methods[e];i.indexOf(r.gatewayId)>-1&&t.repository.removeServerMethod(n,e)}))},e.prototype.handleResultMessage=function(e){var t=e._tag.invocationId,n=e.result,i=e._tag.serverId;return{invocationId:t,result:n,instance:this.repository.getServerById(i).instance,status:Qo.Success,message:""}},e.prototype.handleInvocationError=function(e){if(this.logger.debug("handle invocation error ".concat(JSON.stringify(e))),"_tag"in e){var t=e._tag.invocationId,n=e._tag.serverId,i=this.repository.getServerById(n),o=e.reason;return{invocationId:t,result:e.context,instance:i.instance,status:Qo.Error,message:o}}return{invocationId:"",message:e.message,status:Qo.Error,error:e}},e}();function Pr(e,t,n,i,o,r){var s,a=o.logger.subLogger("gw3-protocol"),c=new Promise((function(e){s=e})),u=t.domain("agm",["subscribed"]),d=new mr(u,n,i,a.subLogger("server")),h=new _r(u,n,a.subLogger("client"));return u.onJoined((function(o){n.addServer(e,t.peerId),o?function(){return oi(this,void 0,void 0,(function(){var e,t,n,o,s,c,u,d,l,p,f;return ri(this,(function(g){switch(g.label){case 0:for(a.info("reconnected - will replay registered methods and subscriptions"),h.drainSubscriptionsCache().forEach((function(e){var t=e.method,n=Object.assign({},e.params);a.info("trying to soft-re-subscribe to method ".concat(t.name,", with params: ").concat(JSON.stringify(n))),r.client.subscribe(t,n,void 0,void 0,e).then((function(){return a.info("soft-subscribing to method ".concat(t.name," DONE"))})).catch((function(e){return a.warn("subscribing to method ".concat(t.name," failed: ").concat(JSON.stringify(e),"}"))}))})),e=[],t=h.drainSubscriptions(),n=function(t){var n=t.method,i=Object.assign({},t.params);a.info("trying to re-subscribe to method ".concat(n.name,", with params: ").concat(JSON.stringify(i))),e.push(r.client.subscribe(n,i,void 0,void 0,t).then((function(){return a.info("subscribing to method ".concat(n.name," DONE"))})))},o=0,s=t;o<s.length;o++)c=s[o],n(c);for(u=i.getList(),i.reset(),d=function(t){var n=t.definition;a.info("re-publishing method ".concat(n.name)),t.stream?e.push(r.server.createStream(n,t.streamCallbacks,void 0,void 0,t.stream).then((function(){return a.info("subscribing to method ".concat(n.name," DONE"))}))):t.theFunction&&t.theFunction.userCallback?e.push(r.register(n,t.theFunction.userCallback).then((function(){return a.info("subscribing to method ".concat(n.name," DONE"))}))):t.theFunction&&t.theFunction.userCallbackAsync&&e.push(r.registerAsync(n,t.theFunction.userCallbackAsync).then((function(){return a.info("subscribing to method ".concat(n.name," DONE"))}))),a.info("re-publishing method ".concat(n.name," DONE"))},l=0,p=u;l<p.length;l++)f=p[l],d(f);return[4,Promise.all(e)];case 1:return g.sent(),a.info("Interop is re-announced"),[2]}}))}))}().then((function(){return t.setLibReAnnounced({name:"interop"})})).catch((function(e){return a.warn("Error while re-announcing interop: ".concat(JSON.stringify(e)))})):s&&(s({client:h,server:d}),s=void 0)})),u.onLeft((function(){n.reset()})),u.join(),c}var Tr=function(){function e(e){var t=this;if(void 0===e)throw new Error("configuration is required");if(void 0===e.connection)throw new Error("configuration.connections is required");var n,i=e.connection;if("number"!=typeof e.methodResponseTimeout&&(e.methodResponseTimeout=3e4),"number"!=typeof e.waitTimeoutMs&&(e.waitTimeoutMs=3e4),this.unwrappedInstance=new cr(this,void 0,i),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new dr(e.logger.subLogger("cRep"),this),this.serverRepository=new hr,3!==i.protocolVersion)throw new Error("protocol ".concat(i.protocolVersion," not supported"));n=Pr(this.instance,i,this.clientRepository,this.serverRepository,e,this),this.readyPromise=n.then((function(n){return t.protocol=n,t.client=new tr(t.protocol,t.clientRepository,t.instance,e),t.server=new ar(t.protocol,t.serverRepository),t}))}return e.prototype.ready=function(){return this.readyPromise},e.prototype.serverRemoved=function(e){return this.client.serverRemoved(e)},e.prototype.serverAdded=function(e){return this.client.serverAdded(e)},e.prototype.serverMethodRemoved=function(e){return this.client.serverMethodRemoved(e)},e.prototype.serverMethodAdded=function(e){return this.client.serverMethodAdded(e)},e.prototype.methodRemoved=function(e){return this.client.methodRemoved(e)},e.prototype.methodAdded=function(e){return this.client.methodAdded(e)},e.prototype.methodsForInstance=function(e){return this.client.methodsForInstance(e)},e.prototype.methods=function(e){return this.client.methods(e)},e.prototype.servers=function(e){return this.client.servers(e)},e.prototype.subscribe=function(e,t,n,i){return this.client.subscribe(e,t,n,i)},e.prototype.createStream=function(e,t,n,i){return this.server.createStream(e,t,n,i)},e.prototype.unregister=function(e){return this.server.unregister(e)},e.prototype.registerAsync=function(e,t){return this.server.registerAsync(e,t)},e.prototype.register=function(e,t){return this.server.register(e,t)},e.prototype.invoke=function(e,t,n,i,o,r){return this.client.invoke(e,t,n,i,o,r)},e.prototype.waitForMethod=function(e){var t=new Ni,n=this.client.methodAdded((function(i){i.name===e&&(n(),t.resolve(i))}));return t.promise},e}(),kr=["subscribed","success"],Mr=function(){function e(e,t){var n=this;this.publish=function(e,t,i){var o=i||{},r=o.routingKey,s=o.target,a=n.removeEmptyValues({type:"publish",topic:e,data:t,peer_id:n.peerId,routing_key:r,target_identity:s});n.session.send(a)},this.subscribe=function(e,t,i){return new Promise((function(o,r){var s=i||{},a=s.routingKey,c=s.target,u=n.removeEmptyValues({type:"subscribe",topic:e,peer_id:n.peerId,routing_key:a,source:c});n.session.send(u).then((function(i){var r=i.subscription_id;n.subscriptions.push({subscription_id:r,topic:e,callback:t,source:c}),o({unsubscribe:function(){return n.session.send({type:"unsubscribe",subscription_id:r,peer_id:n.peerId}),n.subscriptions=n.subscriptions.filter((function(e){return e.subscription_id!==r})),Promise.resolve()}})})).catch((function(e){return r(e)}))}))},this.watchOnEvent=function(){n.session.on("event",(function(e){var t=e.data,i=e.subscription_id,o=e["publisher-identity"],r=n.subscriptions.find((function(e){return e.subscription_id===i}));r&&(r.source?n.keysMatch(r.source,o)&&r.callback(t,r.topic,o):r.callback(t,r.topic,o))}))},this.connection=e,this.logger=t,this.peerId=e.peerId,this.subscriptions=[],this.session=e.domain("bus",kr),this.readyPromise=this.session.join(),this.readyPromise.then((function(){n.watchOnEvent()}))}return e.prototype.ready=function(){return this.readyPromise},e.prototype.removeEmptyValues=function(e){var t={};return Object.keys(e).forEach((function(n){void 0!==e[n]&&null!==e[n]&&(t[n]=e[n])})),t},e.prototype.keysMatch=function(e,t){var n=Object.keys(e),i=!0;return n.forEach((function(n){e[n]!==t[n]&&(i=!1)})),i},e}(),Rr=function(e,t){var n,i,o,r,s,a,c,u,d,h="object"==typeof window?null!==(n=window.iodesktop)&&void 0!==n?n:window.glue42gd:void 0,l="object"==typeof window&&null!==(i=window.gdPreloadPromise)&&void 0!==i?i:Promise.resolve(),p=Wi("glue"),f=function(e,t,n){var i,o,r,s,a;if(Oi.isNode()){var c=process.env._GD_STARTING_CONTEXT_;if(c)try{a=JSON.parse(c)}catch(e){}}function u(){if(e.application)return e.application;if(n)return n.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;var t=go();return Oi.isNode()?a?a.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+" (".concat(t,")"):t}var d=function(){var i,o,r,s,c,d,h,l,p,f,g,m=e.gateway,v=null!==(i=null==m?void 0:m.protocolVersion)&&void 0!==i?i:3,y=null==m?void 0:m.reconnectInterval,b=null==m?void 0:m.reconnectAttempts,w=null==m?void 0:m.ws,I=null==m?void 0:m.sharedWorker,C=null==m?void 0:m.inproc,S=null!==(o=null==m?void 0:m.webPlatform)&&void 0!==o?o:void 0;n&&(w=n.gwURL),Oi.isNode()&&a&&a.gwURL&&(w=a.gwURL),w||I||C||(w="ws://localhost:8385");var x=u(),_=x;void 0!==n?(l=n.windowId,p=n.pid,n.env&&(f=n.env.env,g=n.env.region),_=null!==(r=n.application)&&void 0!==r?r:"glue-app",h=n.appInstanceId):Oi.isNode()?(p=process.pid,a&&(f=a.env,g=a.region,h=a.instanceId)):void 0!==(null===window||void 0===window?void 0:window.glue42electron)&&(l=null===window||void 0===window?void 0:window.glue42electron.instanceId,p=null===window||void 0===window?void 0:window.glue42electron.pid,f=null===window||void 0===window?void 0:window.glue42electron.env,g=null===window||void 0===window?void 0:window.glue42electron.region,_=null!==(s=null===window||void 0===window?void 0:window.glue42electron.application)&&void 0!==s?s:"glue-app",h=null===window||void 0===window?void 0:window.glue42electron.instanceId);var P=null!==(d=null===(c=e.gateway)||void 0===c?void 0:c.replaySpecs)&&void 0!==d?d:[];P.push(Lo);var T={application:_,applicationName:x,windowId:l,instance:h,process:p,region:g,environment:f,api:t.version||qo};return e.identity&&(T=Object.assign(T,e.identity)),{identity:T,reconnectInterval:y,ws:w,sharedWorker:I,webPlatform:S,inproc:C,protocolVersion:v,reconnectAttempts:b,replaySpecs:P}}(),h=u();if("undefined"!=typeof window){var l=window,p=l.htmlContainer?"".concat(l.htmlContainer.containerName,".").concat(l.htmlContainer.application):null===(i=null==l?void 0:l.glue42gd)||void 0===i?void 0:i.application;p&&(h=p)}return{bus:null!==(o=e.bus)&&void 0!==o&&o,application:h,auth:function(){var t,n,i;return"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:Oi.isNode()&&a&&a.gwToken?{gatewayToken:a.gwToken}:(null===(t=e.gateway)||void 0===t?void 0:t.webPlatform)||(null===(n=e.gateway)||void 0===n?void 0:n.inproc)||(null===(i=e.gateway)||void 0===i?void 0:i.sharedWorker)?{username:"glue42",password:"glue42"}:void 0}(),logger:function(){var t,i,o,r=e.logger,s="warn";return r||(r=s),n&&(o=n.consoleLogLevel),"string"==typeof r?{console:null!=o?o:r,publish:s}:{console:null!==(t=null!=o?o:r.console)&&void 0!==t?t:s,publish:null!==(i=r.publish)&&void 0!==i?i:s}}(),connection:d,metrics:null===(r=e.metrics)||void 0===r||r,contexts:void 0===e.contexts||"boolean"==typeof e.contexts&&e.contexts?{reAnnounceKnownContexts:!0}:"object"==typeof e.contexts&&Object.assign({},{reAnnounceKnownContexts:!0},e.contexts),version:t.version||qo,libs:null!==(s=t.libs)&&void 0!==s?s:[],customLogger:e.customLogger}}(e=e||{},t=t||{},h),g={};function m(e,t,n){(d=s.canPublish("trace"))&&s.trace("registering ".concat(e," module"));var i=function(){t.initTime=n.stop(),t.initEndTime=n.endTime,t.marks=n.marks,d&&s.trace("".concat(e," is ready - ").concat(n.endTime-n.startTime))};t.initStartTime=n.startTime,t.ready?t.ready().then((function(){i()})):i(),Array.isArray(e)||(e=[e]),e.forEach((function(e){g[e]=t,Rr[e]=t}))}function v(){var e,t,n,i,r,c=Wi("metrics"),u=f.metrics,d=null==h?void 0:h.getMetricsPublishingEnabled,l=f.connection.identity,p=d||function(){return!0},g=null!==(e="boolean"!=typeof u&&u.disableAutoAppSystem)&&void 0!==e&&e;return m("metrics",a=Ti({connection:u?o:void 0,logger:s.subLogger("metrics"),canUpdateMetric:p,system:"Glue42",service:null!==(n=null!==(t=null==l?void 0:l.service)&&void 0!==t?t:null==h?void 0:h.applicationName)&&void 0!==n?n:f.application,instance:null!==(r=null!==(i=null==l?void 0:l.instance)&&void 0!==i?i:null==l?void 0:l.windowId)&&void 0!==r?r:go(),disableAutoAppSystem:g,pagePerformanceMetrics:"boolean"!=typeof u?null==u?void 0:u.pagePerformanceMetrics:void 0}),c),Promise.resolve()}function y(){var e=f.activities&&3===o.protocolVersion;if(f.contexts||e){var t=Wi("contexts");return m("contexts",c=new Yo({connection:o,logger:s.subLogger("contexts"),trackAllContexts:"object"==typeof f.contexts&&f.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof f.contexts&&f.contexts.reAnnounceKnownContexts}),t),c}var n=o.replayer;n&&n.drain(Lo.name)}function b(){return oi(this,void 0,void 0,(function(){var e;return ri(this,(function(t){return f.bus?(e=Wi("bus"),m("bus",u=new Mr(o,s.subLogger("bus")),e),[2,Promise.resolve()]):[2,Promise.resolve()]}))}))}function w(e){try{return e.forEach((function(e){!function(e,t){var n=Wi(e),i=t(g);i&&m(e,i,n)}(e.name,e.create)})),Promise.resolve()}catch(e){return Promise.reject(e)}}return l.then((function(){var e,t=Wi("logger");return(s=new xo("".concat(null===(e=f.connection.identity)||void 0===e?void 0:e.application),void 0,f.customLogger)).consoleLevel(f.logger.console),s.publishLevel(f.logger.publish),s.canPublish("debug")&&s.debug("initializing glue..."),m("logger",s,t),Promise.resolve(void 0)})).then((function(){var e=Wi("connection");o=new Co(f.connection,s.subLogger("connection"));var t=Promise.resolve(f.auth);return f.connection&&!f.auth&&(h?t=h.getGWToken().then((function(e){return{gatewayToken:e}})):"undefined"!=typeof window&&(null===window||void 0===window?void 0: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((function(t){var 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,o.login(n)})).then((function(){return m("connection",o,e),f})).catch((function(e){throw o&&o.logout(),e}))})).then((function(){return Promise.all([v(),(e=Wi("interop"),t={connection:o,logger:s.subLogger("interop")},r=new Tr(t),xo.Interop=r,m(["interop","agm"],r,e),Promise.resolve()),y(),b()]);var e,t})).then((function(){return r.readyPromise})).then((function(){return function(){return oi(this,void 0,void 0,(function(){var t,n,i;return ri(this,(function(o){switch(o.label){case 0:if(t="T42.ACS.RegisterInstance",!Oi.isNode()||void 0!==process.env._GD_STARTING_CONTEXT_||void 0===(null==e?void 0:e.application))return[3,4];if(!(r.methods({name:t}).length>0))return[3,4];o.label=1;case 1:return o.trys.push([1,3,,4]),[4,r.invoke(t,{appName:null==e?void 0:e.application,pid:process.pid})];case 2:return o.sent(),[3,4];case 3:return n=o.sent(),i=n,s.error("Cannot register as an instance: ".concat(JSON.stringify(i.message))),[3,4];case 4:return[2]}}))}))}()})).then((function(){return w(f.libs||[])})).then((function(){var e=Object.keys(g).map((function(e){var t=g[e];return t.ready?t.ready():Promise.resolve()}));return Promise.all(e)})).then((function(){var n={coreVersion:qo,version:f.version};p.stop();var i={feedback:function(e){r&&r.invoke("T42.ACS.Feedback",e,"best")},info:n,logger:s,interop:r,agm:r,connection:o,metrics:a,contexts:c,bus:u,version:f.version,userConfig:e,done:function(){return null==s||s.info("done called by user..."),o.logout()}};if(i.performance={get glueVer(){return f.version},get glueConfig(){return JSON.stringify(e)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){var e=Di;return Object.keys(e).map((function(t){var n=e[t];return{name:t,duration:n.endTime-n.startTime,marks:n.marks,startTime:n.startTime,endTime:n.endTime}}))}},Object.keys(g).forEach((function(e){var t=g[e];i[e]=t})),i.config={},Object.keys(f).forEach((function(e){i.config[e]=f[e]})),t&&t.extOptions&&Object.keys(t.extOptions).forEach((function(e){i.config[e]=null==t?void 0:t.extOptions[e]})),(null==t?void 0:t.enrichGlue)&&t.enrichGlue(i),h&&h.updatePerfData&&h.updatePerfData(i.performance),i.agm){var d=function(e,t,n){return function(){return i.logger.warn("glue.js - 'glue.agm.".concat(t,"' method is deprecated, use 'glue.interop.").concat(n,"' instead.")),e.apply(i.agm,arguments)}},l=i.agm;l.method_added=d(i.agm.methodAdded,"method_added","methodAdded"),l.method_removed=d(i.agm.methodRemoved,"method_removed","methodRemoved"),l.server_added=d(i.agm.serverAdded,"server_added","serverAdded"),l.server_method_aded=d(i.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),l.server_method_removed=d(i.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return i})).catch((function(e){return Promise.reject({err:e,libs:g})}))};"undefined"!=typeof window&&(window.IOConnectCore=Rr),Rr.version=qo,Rr.default=Rr;const jr=(Ar=Rr,e=>t(void 0,void 0,void 0,(function*(){if(window.glue42gd||window.iodesktop)return(e=>{var t,n,i;const o={windows:!0,layouts:"full",appManager:"full",channels:!0,libraries:null!==(t=null==e?void 0:e.libraries)&&void 0!==t?t:[],logger:null!==(i=null===(n=null==e?void 0:e.systemLogger)||void 0===n?void 0:n.level)&&void 0!==i?i:"warn"};return window.glue42gd,window.Glue(o)})(e);const t=new Zn,i=(e=>{var t,i,o;const r=!!(null===(i=null===(t=null==e?void 0:e.gateway)||void 0===t?void 0:t.webPlatform)||void 0===i?void 0:i.port),s=Object.assign({},n,e,{isPlatformInternal:r});return s.systemLogger&&(s.logger=null!==(o=s.systemLogger.level)&&void 0!==o?o:"info"),s})(e);(()=>{const e=window.glue42core||window.iobrowser;if(e&&e.webStarted)throw new Error("IoConnect Browser has already been started for this application.");e?e.webStarted=!0:window.iobrowser={webStarted:!0}})();const o=yield(r=()=>Ar(i,{version:ei}),s=3e4,a="Glue Web initialization timed out, because core didn't resolve",new Promise(((e,t)=>{let n=!0;const i=setTimeout((()=>{n&&(n=!1,t(a||`Promise timeout hit: ${s}`))}),s);r().then((t=>{n&&(n=!1,clearTimeout(i),e(t))})).catch((e=>{n&&(n=!1,clearTimeout(i),t(e))}))})));var r,s,a;const c=o.logger.subLogger("web.main.controller");return t.defineGlue(o),yield t.preferredConnectionController.start(i),yield t.bridge.start(t.controllers),t.defineConfig(i),c.trace("the bridge has been started, initializing all controllers"),yield Promise.all(Object.values(t.controllers).map((e=>e.start(o,t)))),c.trace("all controllers reported started, starting all additional libraries"),yield Promise.all(i.libraries.map((e=>e(o,i)))),c.trace("all libraries were started"),t.eventsDispatcher.start(o),c.trace("start event dispatched, glue is ready, returning it"),o})));var Ar;if("undefined"!=typeof window){const e=window;e.IOBrowser=jr,delete e.GlueCore,delete e.IOConnectCore}const Er=window.glue42gd||window.glue42core,Or=window.iodesktop||window.iobrowser;return Er||Or||(window.iobrowser={webStarted:!1}),jr.version=ei,jr}));
|