@openfin/core-web 0.46.82 → 0.47.1
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/out/api-client.cjs.js +1 -1
- package/out/api-client.esm.js +1 -1
- package/out/{main-407c3513.js → main-407a2917.js} +1 -1
- package/out/{main-0dd2f710.js → main-6bc6742f.js} +1 -1
- package/out/{main-78cc9512.js → main-773b6c6a.js} +1 -1
- package/out/{main-f276b092.js → main-7f56b5d7.js} +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventEmitter as t}from"events";import{isEqual as e}from"es-toolkit";import{v4 as n}from"uuid";const i=(t,e)=>`${e}<${btoa(JSON.stringify(t))}>`,r=(t,e)=>{try{return t.origin===e.origin}catch(t){return!1}},s=(t,e)=>{const n=new MutationObserver(n=>{let i=!1;n.forEach(t=>{"TITLE"!==t.target.parentNode?.nodeName&&"TITLE"!==t.target.nodeName?(t.removedNodes.forEach(t=>{"TITLE"!==t.nodeName&&"TITLE"!==t.parentNode?.nodeName||(i=!0)}),t.addedNodes.forEach(t=>{"TITLE"!==t.nodeName&&"TITLE"!==t.parentNode?.nodeName||(i=!0)})):i=!0});const r=t.querySelector("title")?.textContent??"";i&&e(r)});return n.observe(t,{childList:!0,subtree:!0,characterData:!0}),n},o=(t,e)=>{let n;const i=new MutationObserver(()=>{(()=>{const i=t.querySelector('link[rel~="icon"]')?.href;i&&i!==n&&(n=i,e(i))})()});return i.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["href","rel"]}),i};var a,c,d=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},h=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class l{constructor(t){this.isNodeEnvironment=()=>"node"===this.wire.environment.type,this.isOpenFinEnvironment=()=>"openfin"===this.wire.environment.type,this.isBrowserEnvironment=()=>"other"===this.wire.environment.type,this.wire=t}get fin(){return this.wire.getFin()}get me(){return this.wire.me}}class p extends l{constructor(t,e,...n){super(t),this.topic=e,a.set(this,void 0),c.set(this,void 0),this.eventNames=()=>this.hasEmitter()?this.getOrCreateEmitter().eventNames():[],this.emit=(t,e,...n)=>!!this.hasEmitter()&&this.getOrCreateEmitter().emit(t,e,...n),this.hasEmitter=()=>this.wire.eventAggregator.has(h(this,a,"f")),this.getOrCreateEmitter=()=>this.wire.eventAggregator.getOrCreate(h(this,a,"f")),this.listeners=t=>this.hasEmitter()?this.getOrCreateEmitter().listeners(t):[],this.listenerCount=t=>this.hasEmitter()?this.getOrCreateEmitter().listenerCount(t):0,this.registerEventListener=async(t,e={},n,i)=>{const r={...this.identity,timestamp:e.timestamp||Date.now(),topic:this.topic,type:t},s=this.getOrCreateEmitter();n(s);try{await this.wire.sendAction("subscribe-to-desktop-event",r)}catch(t){throw i(s),this.deleteEmitterIfNothingRegistered(s),t}},this.deregisterEventListener=async(t,e={})=>{if(this.hasEmitter()){const n={...this.identity,timestamp:e.timestamp||Date.now(),topic:this.topic,type:t};return await this.wire.sendAction("unsubscribe-to-desktop-event",n).catch(()=>null),this.getOrCreateEmitter()}return Promise.resolve()},d(this,a,[e,...n],"f"),d(this,c,new WeakMap,"f")}async on(t,e,n){return await this.registerEventListener(t,n,n=>{n.on(t,e)},n=>{n.removeListener(t,e)}),this}async addListener(t,e,n){return this.on(t,e,n)}async once(t,e,n){const i=()=>this.deregisterEventListener(t);return h(this,c,"f").set(e,i),await this.registerEventListener(t,n,n=>{n.once(t,i),n.once(t,e)},n=>{n.removeListener(t,i),n.removeListener(t,e)}),this}async prependListener(t,e,n){return await this.registerEventListener(t,n,n=>{n.prependListener(t,e)},n=>{n.removeListener(t,e)}),this}async prependOnceListener(t,e,n){const i=()=>this.deregisterEventListener(t);return h(this,c,"f").set(e,i),await this.registerEventListener(t,n,n=>{n.prependOnceListener(t,e),n.once(t,i)},n=>{n.removeListener(t,e),n.removeListener(t,i)}),this}async removeListener(t,e,n){const i=await this.deregisterEventListener(t,n);if(i){i.removeListener(t,e);const n=h(this,c,"f").get(e);n&&i.removeListener(t,n),this.deleteEmitterIfNothingRegistered(i)}return this}async deregisterAllListeners(t){const e={...this.identity,type:t,topic:this.topic};if(this.hasEmitter()){const t=this.getOrCreateEmitter(),n=t.listenerCount(e.type),i=[];for(let t=0;t<n;t++)i.push(this.wire.sendAction("unsubscribe-to-desktop-event",e).catch(()=>null));return await Promise.all(i),t}}async removeAllListeners(t){const e=async t=>{const e=await this.deregisterAllListeners(t);e&&(e.removeAllListeners(t),this.deleteEmitterIfNothingRegistered(e))};if(t)await e(t);else if(this.hasEmitter()){const t=this.getOrCreateEmitter().eventNames();await Promise.all(t.map(e))}return this}deleteEmitterIfNothingRegistered(t){0===t.eventNames().length&&this.wire.eventAggregator.delete(h(this,a,"f"))}}a=new WeakMap,c=new WeakMap;const u=Error;function w(t,e){const n=t.split("\n").filter(t=>t.length>0),i=void 0===n[0]||(r=n[0],/^\s*at\s/.test(r)||r.includes("@"))?0:1;var r;return n.slice(i+e)}class y extends Error{}class f extends Error{}class g extends Error{}class m extends Error{}class v extends Error{constructor(t){const{message:e,name:n,stack:i,...r}=t;super(e),"cause"in t&&t.cause&&(this.cause=new v(t.cause)),this.name=n||"Error",this.stack=i??this.toString(),Object.keys(r).filter(t=>"cause"!==t).forEach(t=>{this[t]=r[t]})}}class C extends Error{static trimEndCallSites(t,e){const n=u.stackTraceLimit,i=u.prepareStackTrace;u.prepareStackTrace=(t,e)=>e;const r="string"==typeof t.stack,s=(r?t.stack?.split("\n"):t.stack)??[];if(u.prepareStackTrace=i,u.stackTraceLimit=n,s.length){const n=[];for(const t of r?s:s.slice(1))if(n.push(t),e.test(t.toString()))break;t.stack=r?n.join("\n"):C.prepareStackTrace(t,n)}}static getCallSite(t=0){const e=u.stackTraceLimit,n=t+1,i="number"==typeof e&&Number.isFinite(e)?e:10,r=u.prepareStackTrace;try{u.stackTraceLimit=i+n,u.prepareStackTrace=(t,e)=>e;const t=(new Error).stack;return Array.isArray(t)?t.slice(n):"string"==typeof t&&t.length>0?w(t,n):[]}finally{u.prepareStackTrace=r,u.stackTraceLimit=e}}static prepareStackTrace(t,e){const n=`${t.name||"Error"}: ${t.message||""}`,i="string"==typeof e?w(e,0):e;if(!Array.isArray(i)||0===i.length)return n;if(function(t){if(!Array.isArray(t)||0===t.length)return Array.isArray(t);const e=t[0];return"object"==typeof e&&null!==e&&"function"==typeof e.getFileName}(i)){const e=u.prepareStackTrace;return"function"==typeof e?e(t,i):`${n}\n${i.map(t=>` at ${t}`).join("\n")}`}return`${n}\n${i.join("\n")}`}constructor(t,e){const{reason:n,error:i}=t;super(n),this.name=this.constructor.name,i?.stack&&(this.cause=new v(i)),e&&(this.stack=C.prepareStackTrace(this,e))}}function I(t){let e;return"object"==typeof t&&"string"==typeof t.uuid||(e="Not a valid identity object"),e}const b=t=>{(t.contentNavigation?.whitelist||t.contentNavigation?.blacklist||t.contentRedirect?.whitelist||t.contentRedirect?.blacklist)&&console.warn("The properties 'whitelist' and 'blacklist' have been marked as deprecated and will be removed in a future version. Please use 'allowlist' and 'denylist'.")};class x extends l{async create(t){const{uuid:e}=this.wire.me;if(!t.name||"string"!=typeof t.name)throw new Error("Please provide a name property as a string in order to create a View.");return b(t),this.wire.environment.childViews?await this.wire.environment.createChildContent({entityType:"view",options:{...t,uuid:e}}):await this.wire.sendAction("create-view",{...t,uuid:e}),this.wrapSync({uuid:e,name:t.name})}async wrap(t){this.wire.recordAnalytic("view-wrap");const e=I(t);if(e)throw new Error(e);return new S(this.wire,t)}wrapSync(t){this.wire.recordAnalytic("view-wrap-sync");const e=I(t);if(e)throw new Error(e);return new S(this.wire,t)}getCurrent(){if(this.wire.recordAnalytic("view-get-current"),!this.wire.me.isView)throw new Error("You are not in a View context");const{uuid:t,name:e}=this.wire.me;return this.wrap({uuid:t,name:e})}getCurrentSync(){if(this.wire.recordAnalytic("view-get-current-sync"),!this.wire.me.isView)throw new Error("You are not in a View context");const{uuid:t,name:e}=this.wire.me;return this.wrapSync({uuid:t,name:e})}}class A{constructor(t){this.producerFn=t}getValue(){return this.value||(this.value=this.producerFn()),this.value}}class E{constructor(t){this.producerFn=t}async getValue(){return this.promise||(this.promise=this.producerFn().catch(t=>{throw delete this.promise,t})),this.promise}}class P extends p{constructor(t,e,n){super(t,n,e.uuid,e.name),this.identity=e,this.entityType=n}capturePage(t){return this.wire.sendAction("capture-page",{options:t,...this.identity}).then(({payload:t})=>t.data)}executeJavaScript(t){return this.wire.sendAction("execute-javascript-in-window",{...this.identity,code:t}).then(({payload:t})=>t.data)}getZoomLevel(){return this.wire.sendAction("get-zoom-level",this.identity).then(({payload:t})=>t.data)}setZoomLevel(t){return this.wire.sendAction("set-zoom-level",{...this.identity,level:t}).then(()=>{})}async translatePage(t){await this.wire.sendAction("translate-page",{...this.identity,...t})}async revertTranslation(){await this.wire.sendAction("revert-translation",this.identity)}async getTranslationState(){const{payload:t}=await this.wire.sendAction("get-translation-state",this.identity);return t.data}navigate(t){return this.wire.sendAction("navigate-window",{...this.identity,url:t}).then(()=>{})}navigateBack(){return this.wire.sendAction("navigate-window-back",{...this.identity}).then(()=>{})}async navigateForward(){await this.wire.sendAction("navigate-window-forward",{...this.identity})}stopNavigation(){return this.wire.sendAction("stop-window-navigation",{...this.identity}).then(()=>{})}reload(t=!1){return this.wire.sendAction("reload-window",{ignoreCache:t,...this.identity}).then(()=>{})}print(t={}){return this.wire.sendAction("print",{...this.identity,options:t}).then(()=>{})}findInPage(t,e){return this.wire.sendAction("find-in-page",{...this.identity,searchTerm:t,options:e}).then(({payload:t})=>t.data)}stopFindInPage(t){return this.wire.sendAction("stop-find-in-page",{...this.identity,action:t}).then(()=>{})}getPrinters(){return this.wire.sendAction("get-printers",{...this.identity}).then(({payload:t})=>t.data)}async focus({emitSynthFocused:t}={emitSynthFocused:!0}){await this.wire.sendAction("focus-window",{emitSynthFocused:t,...this.identity})}async showDeveloperTools(){await this.wire.sendAction("show-developer-tools",this.identity)}async getProcessInfo(){const{payload:{data:t}}=await this.wire.sendAction("get-process-info",this.identity);return t}async getSharedWorkers(){return this.wire.sendAction("get-shared-workers",this.identity).then(({payload:t})=>t.data)}async inspectSharedWorker(){await this.wire.sendAction("inspect-shared-worker",{...this.identity})}async inspectSharedWorkerById(t){await this.wire.sendAction("inspect-shared-worker-by-id",{...this.identity,workerId:t})}async inspectServiceWorker(){await this.wire.sendAction("inspect-service-worker",{...this.identity})}async showPopupWindow(t){if(this.wire.recordAnalytic(`${this.entityType}-show-popup-window`),t?.onPopupReady){const e=async({popupName:e})=>{try{const n=this.fin.Window.wrapSync({uuid:this.fin.me.uuid,name:e});await t.onPopupReady(n)}catch(t){throw new Error(`Something went wrong during onPopupReady execution: ${t}`)}};await this.once("popup-ready",e)}const{payload:e}=await this.wire.sendAction("try-create-popup-window",{options:{...t,hasResultCallback:!!t?.onPopupResult,hasReadyCallback:!!t?.onPopupReady},...this.identity}),{data:{willOpen:n,options:i}}=e;n&&await this.fin.Window.create(i.initialOptions);if(t?.onPopupResult){const e=async e=>{await t.onPopupResult((t=>{const{name:e,uuid:n,result:i,data:r}=t,s={identity:{name:e,uuid:n},result:i};return r&&(s.data=r),s})(e))},n=async()=>{await this.removeListener("popup-result",e)};await this.on("popup-result",e),await this.once("popup-teardown",n)}const{payload:r}=await this.wire.sendAction("show-popup-window",{options:i,...this.identity});return r.data}async getScreenCapturePermission(){return(await this.wire.sendAction("get-screen-capture-permissions",this.identity)).payload.data}}var M;class S extends P{constructor(t,e){super(t,e,"view"),this.identity=e,M.set(this,new A(()=>this.fin.Platform.wrapSync(this.identity).getClient())),this.attach=async t=>{await this.wire.sendAction("attach-view",{target:t,...this.identity})},this.destroy=async()=>{await this.wire.sendAction("destroy-view",{...this.identity})},this.show=async()=>{await this.wire.sendAction("show-view",{...this.identity})},this.showAt=async(t,e={})=>{await this.wire.sendAction("show-view-at",{bounds:t,...this.identity,options:e})},this.bringToFront=async()=>{await this.wire.sendAction("bring-view-to-front",{...this.identity})},this.hide=async()=>{await this.wire.sendAction("hide-view",{...this.identity})},this.setBounds=async t=>{await this.wire.sendAction("set-view-bounds",{bounds:t,...this.identity})},this.getBounds=async()=>(await this.wire.sendAction("get-view-bounds",{...this.identity})).payload.data,this.getInfo=async()=>(await this.wire.sendAction("get-view-info",{...this.identity})).payload.data,this.getParentLayout=async()=>(this.wire.recordAnalytic("view-get-parent-layout"),this.fin.Platform.Layout.getLayoutByViewIdentity(this.identity)),this.getOptions=async()=>this.wire.sendAction("get-view-options",{...this.identity}).then(({payload:t})=>t.data),this.updateOptions=async t=>this.wire.sendAction("update-view-options",{options:t,...this.identity}).then(()=>{}),this.getCurrentWindow=async()=>{const{payload:{data:t}}=await this.wire.sendAction("get-view-window",{...this.identity});return new L(this.wire,t)},this.getCurrentStack=async()=>{this.wire.recordAnalytic("view-get-current-stack");try{return(await this.getParentLayout()).getStackByViewIdentity(this.identity)}catch(t){throw new C({reason:"This view does not belong to a stack.",error:t})}},this.triggerBeforeUnload=async()=>(await this.wire.sendAction("trigger-before-unload",{...this.identity})).payload.data,this.bindToElement=async t=>{if(!t)throw new Error("Element not found.");return this.wire.environment.observeBounds(t,async t=>this.setBounds(t))}}async focus({emitSynthFocused:t}={emitSynthFocused:!0}){const e=await this.getCurrentWindow();await e.focusedWebViewWasChanged(),await super.focus({emitSynthFocused:t})}}M=new WeakMap;class k extends p{constructor(t,e){super(t,"application",e.uuid),this.identity=e,this.getPerformanceStats=async(t={})=>{const{include:e,resources:n=!0,browser:i=!1}=t,r=await this.wire.sendAction("get-application-performance-stats",{...this.identity,...void 0!==e?{include:(t=>t.map(t=>t instanceof RegExp?{type:"regex",expression:t.source,flags:t.flags}:t))(e)}:{},resources:n,browser:i});return r.payload.data},this.window=new L(this.wire,{uuid:this.identity.uuid,name:this.identity.uuid})}windowListFromIdentityList(t){const e=[];return t.forEach(t=>{e.push(new L(this.wire,{uuid:t.uuid,name:t.name}))}),e}isRunning(){return this.wire.sendAction("is-application-running",this.identity).then(({payload:t})=>t.data)}async quit(t=!1){try{await this._close(t),await this.wire.sendAction("destroy-application",{force:t,...this.identity})}catch(t){if(!["Remote connection has closed","Could not locate the requested application"].some(e=>t.message.includes(e)))throw t}}async _close(t=!1){try{await this.wire.sendAction("close-application",{force:t,...this.identity})}catch(t){if(!t.message.includes("Remote connection has closed"))throw t}}close(t=!1){return console.warn("Deprecation Warning: Application.close is deprecated Please use Application.quit"),this.wire.recordAnalytic("application-close"),this._close(t)}getChildWindows(){return this.wire.sendAction("get-child-windows",this.identity).then(({payload:t})=>{const e=[];return t.data.forEach(t=>{e.push({uuid:this.identity.uuid,name:t})}),this.windowListFromIdentityList(e)})}getManifest(){return this.wire.sendAction("get-application-manifest",this.identity).then(({payload:t})=>t.data)}getParentUuid(){return this.wire.sendAction("get-parent-application",this.identity).then(({payload:t})=>t.data)}getShortcuts(){return this.wire.sendAction("get-shortcuts",this.identity).then(({payload:t})=>t.data)}async getViews(){const{payload:t}=await this.wire.sendAction("application-get-views",this.identity);return t.data.map(t=>new S(this.wire,t))}getZoomLevel(){return this.wire.sendAction("get-application-zoom-level",this.identity).then(({payload:t})=>t.data)}getWindow(){return this.wire.recordAnalytic("application-get-window"),Promise.resolve(this.window)}registerUser(t,e){return this.wire.sendAction("register-user",{userName:t,appName:e,...this.identity}).then(()=>{})}removeTrayIcon(){return this.wire.sendAction("remove-tray-icon",this.identity).then(()=>{})}restart(){return this.wire.sendAction("restart-application",this.identity).then(()=>{})}run(){return console.warn("Deprecation Warning: Application.run is deprecated Please use fin.Application.start"),this.wire.recordAnalytic("application-run"),this._run()}_run(t={}){return this.wire.sendAction("run-application",{manifestUrl:this._manifestUrl,opts:t,...this.identity}).then(()=>{})}scheduleRestart(){return this.wire.sendAction("relaunch-on-close",this.identity).then(()=>{})}async sendApplicationLog(){const{payload:t}=await this.wire.sendAction("send-application-log",this.identity);return t.data}async setJumpList(t){await this.wire.sendAction("set-jump-list",{config:t,...this.identity})}setTrayIcon(t){return this.wire.sendAction("set-tray-icon",{enabledIcon:t,...this.identity}).then(()=>{})}async setTrayIconToolTip(t){await this.wire.sendAction("set-tray-icon-tooltip",{...this.identity,toolTip:t})}setShortcuts(t){return this.wire.sendAction("set-shortcuts",{data:t,...this.identity}).then(()=>{})}async setShortcutQueryParams(t){await this.wire.sendAction("set-shortcut-query-args",{data:t,...this.identity})}setZoomLevel(t){return this.wire.sendAction("set-application-zoom-level",{level:t,...this.identity}).then(()=>{})}async setAppLogUsername(t){await this.wire.sendAction("set-app-log-username",{data:t,...this.identity})}getTrayIconInfo(){return this.wire.sendAction("get-tray-icon-info",this.identity).then(({payload:t})=>t.data)}hasTrayIcon(){return this.wire.sendAction("has-tray-icon",this.identity).then(({payload:t})=>t.data)}terminate(){return this.wire.sendAction("terminate-application",this.identity).then(()=>{})}wait(){return this.wire.sendAction("wait-for-hung-application",this.identity).then(()=>{})}getInfo(){return this.wire.sendAction("get-info",this.identity).then(({payload:t})=>t.data)}async getProcessInfo(){const{payload:{data:t}}=await this.wire.sendAction("application-get-process-info",this.identity);return t}async setFileDownloadLocation(t){const{name:e}=this.wire.me,n={uuid:this.identity.uuid,name:e};await this.wire.sendAction("set-file-download-location",{...n,downloadLocation:t})}async getFileDownloadLocation(){const{payload:{data:t}}=await this.wire.sendAction("get-file-download-location",this.identity);return t}async showTrayIconPopupMenu(t){const{name:e}=this.wire.me,n={uuid:this.identity.uuid,name:e},{payload:i}=await this.wire.sendAction("show-tray-icon-popup-menu",{...n,options:t});return i.data}async closeTrayIconPopupMenu(){const{name:t}=this.wire.me,e={uuid:this.identity.uuid,name:t};await this.wire.sendAction("close-tray-icon-popup-menu",{...e})}}class T extends l{async wrap(t){this.wire.recordAnalytic("wrap-application");const e=I(t);if(e)throw new Error(e);return new k(this.wire,t)}wrapSync(t){this.wire.recordAnalytic("wrap-application-sync");const e=I(t);if(e)throw new Error(e);return new k(this.wire,t)}async _create(t){return void 0===t.waitForPageLoad&&(t.waitForPageLoad=!1),void 0===t.autoShow&&void 0===t.isPlatformController&&(t.autoShow=!0),await this.wire.sendAction("create-application",t),this.wrap({uuid:t.uuid})}create(t){return console.warn("Deprecation Warning: fin.Application.create is deprecated. Please use fin.Application.start"),this.wire.recordAnalytic("application-create"),this._create(t)}async start(t){this.wire.recordAnalytic("start-application");const e=await this._create(t);return await this.wire.sendAction("run-application",{uuid:t.uuid}),e}async startManyManifests(t,e){return this.wire.sendAction("run-applications",{applications:t,opts:e}).then(()=>{})}getCurrent(){return this.wire.recordAnalytic("get-current-application"),this.wrap({uuid:this.wire.me.uuid})}getCurrentSync(){return this.wire.recordAnalytic("get-current-application-sync"),this.wrapSync({uuid:this.wire.me.uuid})}async startFromManifest(t,e){this.wire.recordAnalytic("application-start-from-manifest");const n=await this._createFromManifest(t);return await n._run(e),n}createFromManifest(t){return console.warn("Deprecation Warning: fin.Application.createFromManifest is deprecated. Please use fin.Application.startFromManifest"),this.wire.recordAnalytic("application-create-from-manifest"),this._createFromManifest(t)}_createFromManifest(t){return this.wire.sendAction("get-application-manifest",{manifestUrl:t}).then(({payload:t})=>{const e=t.data.platform?t.data.platform.uuid:t.data.startup_app.uuid;return this.wrap({uuid:e})}).then(e=>(e._manifestUrl=t,e))}}class L extends P{constructor(t,e){super(t,e,"window")}async createWindow(t){this.wire.recordAnalytic("window-create-window");const e=await(async(t,e,n=()=>!0,i)=>{let r,s,o;const a=new Promise((t,e)=>{r=t,s=e}),c=t=>{n(t)&&(clearTimeout(o),r(t))};return await t.on(e,c),i&&(o=setTimeout(()=>s(new Error("event timed out")),i)),a.finally(()=>{t.removeListener(e,c).catch(()=>null)}),{getValue:()=>a}})(this,"fire-constructor-callback");void 0===t.waitForPageLoad&&(t.waitForPageLoad=!1),void 0===t.autoShow&&(t.autoShow=!0),b(t);const n=this.wire.environment.createChildContent({entityType:"window",options:t}),[i]=await Promise.all([e.getValue(),n]);let r;const{success:s}=i,o=i.data,{message:a}=o;r=s?{httpResponseCode:o.httpResponseCode,apiInjected:o.apiInjected}:{message:o.message,networkErrorCode:o.networkErrorCode,stack:o.stack};const c={message:a,cbPayload:r,success:s};try{this.getWebWindow().fin.__internal_.openerSuccessCBCalled()}catch(t){}return c.success?this:Promise.reject(c)}getAllFrames(){return this.wire.sendAction("get-all-frames",this.identity).then(({payload:t})=>t.data)}activateAndFocus(t){return this.wire.sendAction("activate-window-and-focus",{winIdentity:this.identity,focusIdentity:t}).then(({payload:t})=>t.data)}getBounds(t){return this.wire.sendAction("get-window-bounds",{...this.identity,options:t}).then(({payload:t})=>t.data)}center(){return this.wire.sendAction("center-window",this.identity).then(()=>{})}blur(){return this.wire.sendAction("blur-window",this.identity).then(()=>{})}bringToFront(){return this.wire.sendAction("bring-window-to-front",this.identity).then(()=>{})}animate(t,e){return this.wire.sendAction("animate-window",{transitions:t,options:e,...this.identity}).then(()=>{})}hide(){return this.wire.sendAction("hide-window",this.identity).then(()=>{})}close(t=!1){return this.wire.sendAction("close-window",{force:t,...this.identity}).then(()=>{Object.setPrototypeOf(this,null)})}focusedWebViewWasChanged(){return this.wire.sendAction("focused-webview-changed",this.identity).then(()=>{})}getNativeId(){return this.wire.sendAction("get-window-native-id",this.identity).then(({payload:t})=>t.data)}async getCurrentViews(){const{payload:t}=await this.wire.sendAction("window-get-views",this.identity);return t.data.map(t=>new S(this.wire,t))}disableFrame(){return console.warn("Function is deprecated; use disableUserMovement instead."),this.wire.sendAction("disable-window-frame",this.identity).then(()=>{})}disableUserMovement(){return this.wire.sendAction("disable-window-frame",this.identity).then(()=>{})}enableFrame(){return console.warn("Function is deprecated; use enableUserMovement instead."),this.wire.sendAction("enable-window-frame",this.identity).then(()=>{})}enableUserMovement(){return this.wire.sendAction("enable-window-frame",this.identity).then(()=>{})}flash(){return this.wire.sendAction("flash-window",this.identity).then(()=>{})}stopFlashing(){return this.wire.sendAction("stop-flash-window",this.identity).then(()=>{})}getInfo(){return this.wire.sendAction("get-window-info",this.identity).then(({payload:t})=>t.data)}async getLayout(t){this.wire.recordAnalytic("window-get-layout");const e=await this.getOptions();if(!e.layout&&!e.layoutSnapshot)throw new Error("Window does not have a Layout");return this.fin.Platform.Layout.wrap(t??this.identity)}getOptions(){return this.wire.sendAction("get-window-options",this.identity).then(({payload:t})=>t.data)}getParentApplication(){return this.wire.recordAnalytic("window-get-parent-application"),Promise.resolve(new k(this.wire,this.identity))}getParentWindow(){return this.wire.recordAnalytic("window-get-parent-window"),Promise.resolve(new k(this.wire,this.identity)).then(t=>t.getWindow())}async getSnapshot(t){const e={area:t,...this.identity};console.warn("Window.getSnapshot has been deprecated, please use Window.capturePage");return(await this.wire.sendAction("get-window-snapshot",e)).payload.data}getState(){return this.wire.sendAction("get-window-state",this.identity).then(({payload:t})=>t.data)}getWebWindow(){return this.wire.recordAnalytic("window-get-web-window"),this.wire.environment.getWebWindow(this.identity)}isMainWindow(){return this.wire.recordAnalytic("window-is-main-window"),this.me.uuid===this.me.name}isShowing(){return this.wire.sendAction("is-window-showing",this.identity).then(({payload:t})=>t.data)}maximize(){return this.wire.sendAction("maximize-window",this.identity).then(()=>{})}minimize(){return this.wire.sendAction("minimize-window",this.identity).then(()=>{})}moveBy(t,e,n){return this.wire.sendAction("move-window-by",{deltaLeft:t,deltaTop:e,positioningOptions:n,...this.identity}).then(()=>{})}moveTo(t,e,n){return this.wire.sendAction("move-window",{left:t,top:e,positioningOptions:n,...this.identity}).then(()=>{})}resizeBy(t,e,n,i){return this.wire.sendAction("resize-window-by",{deltaWidth:Math.floor(t),deltaHeight:Math.floor(e),anchor:n,positioningOptions:i,...this.identity}).then(()=>{})}resizeTo(t,e,n,i){return this.wire.sendAction("resize-window",{width:Math.floor(t),height:Math.floor(e),anchor:n,positioningOptions:i,...this.identity}).then(()=>{})}restore(){return this.wire.sendAction("restore-window",this.identity).then(()=>{})}setAsForeground(){return this.wire.sendAction("set-foreground-window",this.identity).then(()=>{})}setBounds(t,e){return this.wire.sendAction("set-window-bounds",{...t,...this.identity,positioningOptions:e}).then(()=>{})}show(t=!1){return this.wire.sendAction("show-window",{force:t,...this.identity}).then(()=>{})}showAt(t,e,n=!1){return this.wire.sendAction("show-at-window",{force:n,left:Math.floor(t),top:Math.floor(e),...this.identity}).then(()=>{})}updateOptions(t){return"frame"in t&&console.warn("Deprecation Warning: Starting with version 45 it will not be possible to change the frame value after window has been created."),this.wire.sendAction("update-window-options",{options:t,...this.identity}).then(()=>{})}authenticate(t,e){return this.wire.sendAction("window-authenticate",{userName:t,password:e,...this.identity}).then(()=>{})}async showPopupMenu(t){const{payload:e}=await this.wire.sendAction("show-popup-menu",{options:t,...this.identity});return e.data}async closePopupMenu(){return this.wire.sendAction("close-popup-menu",{...this.identity}).then(()=>{})}async dispatchPopupResult(t){this.wire.recordAnalytic("window-dispatch-popup-result"),await this.wire.sendAction("dispatch-popup-result",{data:t,...this.identity})}async print(t={content:"self"}){switch(t.content){case void 0:case"self":return super.print(t);case"screenshot":return this.wire.sendAction("print-screenshot",this.identity).then(()=>{});case"views":return this.wire.sendAction("print-views",{...this.identity,options:t}).then(()=>{});default:return}}async showDownloadBubble(t){return this.wire.sendAction("show-download-bubble",{...this.identity,anchor:t}).then(()=>{})}async updateDownloadBubbleAnchor(t){return this.wire.sendAction("update-download-bubble-anchor",{...this.identity,anchor:t}).then(()=>{})}}class $ extends l{async wrap(t){this.wire.recordAnalytic("window-wrap");const e=I(t);if(e)throw new Error(e);return new L(this.wire,t)}wrapSync(t){this.wire.recordAnalytic("window-wrap-sync");const e=I(t);if(e)throw new Error(e);return new L(this.wire,t)}create(t){this.wire.recordAnalytic("create-window");return new L(this.wire,{uuid:this.me.uuid,name:t.name}).createWindow(t)}getCurrent(){if(this.wire.recordAnalytic("get-current-window"),!this.wire.me.isWindow)throw new Error("You are not in a Window context");const{uuid:t,name:e}=this.wire.me;return this.wrap({uuid:t,name:e})}getCurrentSync(){if(this.wire.recordAnalytic("get-current-window-sync"),!this.wire.me.isWindow)throw new Error("You are not in a Window context");const{uuid:t,name:e}=this.wire.me;return this.wrapSync({uuid:t,name:e})}}class F extends l{async getCategories(){const{payload:t}=await this.wire.sendAction("content-tracing-get-categories");return t.data}async startRecording(t){await this.wire.sendAction("content-tracing-start-recording",{options:t})}async stopRecording(){const{payload:t}=await this.wire.sendAction("content-tracing-stop-recording");return t.data}async getTraceBufferUsage(){const{payload:t}=await this.wire.sendAction("content-tracing-get-trace-buffer-usage");return t.data}}var G,R,O,W,j,N,H=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)},B=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n};const D=(t,e)=>e&&"object"==typeof e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e).sort()):e;class V extends p{constructor(t){super(t,"system"),G.add(this),R.set(this,new Set),O.set(this,new Set),W.set(this,[]),j.set(this,!1),this.ContentTracing=new F(t)}sendExternalProcessRequest(t,e){return new Promise((n,i)=>{const r="external-process-exited";let s,o,a,c;"function"==typeof e.listener&&(a=t=>{const n=t||{};o={topic:"exited",uuid:n.processUuid||"",exitCode:n.exitCode||0},s===t.processUuid&&(e.listener(o),c.removeListener(r,a))},this.wire.me.name||(this.wire.me.name=this.wire.me.uuid),c=new L(this.wire,this.wire.me),c.on(r,a)),this.wire.sendAction(t,e).then(({payload:t})=>{s=t.data.uuid,n(t.data),o&&s===o.uuid&&(e.listener(o),c.removeListener(r,a))}).catch(t=>{c&&c.removeListener(r,a),i(t)})})}getVersion(){return this.wire.sendAction("get-version").then(({payload:t})=>t.data)}clearCache(t){return this.wire.sendAction("clear-cache",t).then(()=>{})}clearHTTPCache(){return this.wire.sendAction("clear-http-cache").then(()=>{})}clearCacheData(t){return this.wire.sendAction("clear-cache-data",t||{}).then(()=>{})}deleteCacheOnExit(){return this.wire.sendAction("delete-cache-request").then(()=>{})}exit(){return this.wire.sendAction("exit-desktop").then(()=>{})}async fetchManifest(t){const{payload:{data:e}}=await this.wire.sendAction("fetch-manifest",{manifestUrl:t});return e}flushCookieStore(){return this.wire.sendAction("flush-cookie-store").then(()=>{})}getAllWindows(){return this.wire.sendAction("get-all-windows").then(({payload:t})=>t.data)}getAllApplications(){return this.wire.sendAction("get-all-applications").then(({payload:t})=>t.data)}getCommandLineArguments(){return this.wire.sendAction("get-command-line-arguments").then(({payload:t})=>t.data)}async getCrashReporterState(){const{payload:{data:{diagnosticMode:t,isRunning:e}}}=await this.wire.sendAction("get-crash-reporter-state");return console.warn("diagnosticMode property is deprecated. It will be removed in a future version"),{diagnosticMode:t,diagnosticsMode:t,isRunning:e}}async startCrashReporter(t){const e=t,n={...e,diagnosticMode:e.diagnosticsMode||e.diagnosticMode},{payload:{data:{diagnosticMode:i,isRunning:r}}}=await this.wire.sendAction("start-crash-reporter",n);return{diagnosticMode:i,diagnosticsMode:i,isRunning:r}}getUniqueUserId(){return this.wire.sendAction("get-unique-user-id").then(({payload:t})=>t.data)}getEntityInfo(t,e){return this.wire.sendAction("get-entity-info",{uuid:t,name:e}).then(({payload:t})=>t.data)}getEnvironmentVariable(t){return this.wire.sendAction("get-environment-variable",{environmentVariables:t}).then(({payload:t})=>t.data)}getFocusedWindow(){return this.wire.sendAction("get-focused-window").then(({payload:t})=>t.data)}getFocusedContent(){return this.wire.sendAction("get-focused-content").then(({payload:t})=>t.data)}async isAppCertified(t){const{payload:{data:{certifiedInfo:e}}}=await this.wire.sendAction("is-app-certified",{manifestUrl:t});return e}getInstalledRuntimes(){return this.wire.sendAction("get-installed-runtimes").then(({payload:t})=>t.data.runtimes)}async getInstalledApps(){const{payload:{data:{installedApps:t}}}=await this.wire.sendAction("get-installed-apps");return t}getLog(t){return this.wire.sendAction("view-log",t).then(({payload:t})=>t.data)}getMachineId(){return this.wire.sendAction("get-machine-id").then(({payload:t})=>t.data)}getMinLogLevel(){return this.wire.sendAction("get-min-log-level").then(({payload:t})=>t.data)}getLogList(){return this.wire.sendAction("list-logs").then(({payload:t})=>t.data)}getMonitorInfo(){return this.wire.sendAction("get-monitor-info").then(({payload:t})=>t.data)}getMousePosition(){return this.wire.sendAction("get-mouse-position").then(({payload:t})=>t.data)}getProcessList(){return console.warn("System.getProcessList has been deprecated. Please consider using our new process APIs: Window.getProcessInfo, View.getProcessInfo, Application.getProcessInfo, System.getAllProcessInfo"),this.wire.sendAction("process-snapshot").then(({payload:t})=>t.data)}async getAllProcessInfo(){const{payload:{data:t}}=await this.wire.sendAction("get-all-process-info",this.identity);return t}getProxySettings(){return this.wire.sendAction("get-proxy-settings").then(({payload:t})=>t.data)}getRuntimeInfo(){return this.wire.sendAction("get-runtime-info").then(({payload:t})=>t.data)}getRvmInfo(){return this.wire.sendAction("get-rvm-info").then(({payload:t})=>t.data)}getHostSpecs(){return this.wire.sendAction("get-host-specs").then(({payload:t})=>t.data)}getOSInfo(){return this.wire.sendAction("get-os-info").then(({payload:t})=>t.data)}launchExternalProcess(t){return this.sendExternalProcessRequest("launch-external-process",t)}monitorExternalProcess(t){return this.sendExternalProcessRequest("monitor-external-process",t)}log(t,e,n){return this.wire.sendAction("write-to-log",{level:t,message:e,target:n??{}}).then(()=>{})}openUrlWithBrowser(t){return this.wire.sendAction("open-url-with-browser",{url:t}).then(()=>{})}async registerCustomProtocol(t){if("object"!=typeof t)throw new Error("Must provide an object with a `protocolName` property having a string value.");await this.wire.sendAction("register-custom-protocol",t)}async unregisterCustomProtocol(t){await this.wire.sendAction("unregister-custom-protocol",{protocolName:t})}async getCustomProtocolState(t){return this.wire.sendAction("get-custom-protocol-state",{protocolName:t}).then(({payload:t})=>t.data)}releaseExternalProcess(t){return this.wire.sendAction("release-external-process",{uuid:t}).then(()=>{})}showDeveloperTools(t){return this.wire.sendAction("show-developer-tools",t).then(()=>{})}terminateExternalProcess(t){return this.wire.sendAction("terminate-external-process",t).then(()=>{})}updateProxySettings(t){return this.wire.sendAction("update-proxy",t).then(()=>{})}async downloadAsset(t,e){const n=()=>{};let i=n,r=n;const s=new Promise((t,e)=>{i=t,r=e});if("openfin"!==this.wire.environment.type)throw new m("downloadAsset only supported in an OpenFin Render process");const o=C.getCallSite(),a=this.wire.environment.getNextMessageId().toString(),c=`asset-download-progress-${a}`,d=`asset-download-error-${a}`,h=`asset-download-complete-${a}`,l=t=>{const n={downloadedBytes:t.downloadedBytes,totalBytes:t.totalBytes};e(n)},p=()=>{this.removeListener(c,l)};await Promise.all([this.on(c,l),this.once(d,t=>{p();const{reason:e,err:n}=t;r(new C({reason:e,error:n},o))}),this.once(h,()=>{p(),i()})]);const u=Object.assign(t,{downloadId:a});return await this.wire.sendAction("download-asset",u).catch(t=>{throw p(),t}),s}downloadRuntime(t,e){const n=C.getCallSite();return new Promise((i,r)=>{if("openfin"!==this.wire.environment.type)return void r(new m("downloadRuntime only supported in an OpenFin Render process"));const s=this.wire.environment.getNextMessageId().toString(),o=`runtime-download-progress-${s}`,a=`runtime-download-error-${s}`,c=`runtime-download-complete-${s}`,d=t=>{const n={downloadedBytes:t.downloadedBytes,totalBytes:t.totalBytes};e(n)},h=()=>{this.removeListener(o,d)};this.on(o,d),this.once(a,t=>{h();const{reason:e,err:i}=t;r(new C({reason:e,error:i},n))}),this.once(c,()=>{h(),i()});const l=Object.assign(t,{downloadId:s});this.wire.sendAction("download-runtime",l).catch(t=>{h(),r(t)})})}downloadPreloadScripts(t){return this.wire.sendAction("download-preload-scripts",{scripts:t}).then(({payload:t})=>t.data)}getAllExternalApplications(){return this.wire.sendAction("get-all-external-applications").then(({payload:t})=>t.data)}getAppAssetInfo(t){return this.wire.sendAction("get-app-asset-info",t).then(({payload:t})=>t.data)}getCookies(t){const e=this.wire.environment.getUrl(),n=Object.assign(t,{url:e});return this.wire.sendAction("get-cookies",n).then(({payload:t})=>t.data)}setMinLogLevel(t){return this.wire.sendAction("set-min-log-level",{level:t}).then(()=>{})}resolveUuid(t){return this.wire.sendAction("resolve-uuid",{entityKey:t}).then(({payload:t})=>t.data)}executeOnRemote(t,e){return e.requestingIdentity=t,this.wire.ferryAction(e)}readRegistryValue(t,e,n){return this.wire.sendAction("read-registry-value",{rootKey:t,subkey:e,value:n}).then(({payload:t})=>t.data)}registerExternalConnection(t){return this.wire.sendAction("register-external-connection",{uuid:t}).then(({payload:t})=>t.data)}async getServiceConfiguration(t){if("string"!=typeof t.name)throw new Error("Must provide an object with a `name` property having a string value");const{name:e}=t;return this.wire.sendAction("get-service-configuration",{name:e}).then(({payload:t})=>t.data)}async getSystemAppConfig(t){if("string"!=typeof t)throw new Error("Must provide a string value for name of system app");return this.wire.sendAction("get-system-app-configuration",{name:t}).then(({payload:t})=>t.data)}async registerShutdownHandler(t){this.wire.recordAnalytic("system-register-shutdown-handler");const{uuid:e,name:n}=this.wire.me;this.on("system-shutdown",i=>{t({proceed:()=>{this.wire.environment.raiseEvent("application/system-shutdown-handled",{uuid:e,name:n,topic:"application"})}})})}runRvmHealthCheck(){return this.wire.sendAction("run-rvm-health-check").then(({payload:t})=>t.data)}async launchManifest(e,n={}){const{subscribe:i,...r}=n,s=r;if(i){const e=new t;i(e);const n="app-version-progress",r="runtime-status",o="app-version-complete",a="app-version-error",c=this.wire.environment.getNextMessageId().toString();s.appVersionId=c;const d=[o,n,r,a],h=t=>{const{appVersionId:e,topic:n,type:i,...r}=t;return{...r,type:d.find(t=>i.includes(t))}},l=t=>{const n=h(t);e.emit(n.type,n)},p=()=>{this.removeListener(`${n}.${c}`,l),this.removeListener(`${r}.${c}`,l),this.removeListener(`${o}.${c}`,l),this.removeListener(`${a}.${c}`,l),this.removeListener(`${o}.${c}`,p),this.removeListener(`${a}.${c}`,p)};await Promise.all([this.on(`${n}.${c}`,l),this.on(`${r}.${c}`,l),this.once(`${o}.${c}`,l),this.once(`${a}.${c}`,l),this.once(`${o}.${c}`,p),this.once(`${a}.${c}`,p)])}return(await this.wire.sendAction("launch-manifest",{manifestUrl:e,opts:s})).payload.data.manifest}async queryPermissionForCurrentContext(t){const e={uuid:this.wire.me.uuid,name:this.wire.me.name};return(await this.wire.sendAction("query-permission-for-current-context",{apiName:t,identity:e})).payload.data}async enableNativeWindowIntegrationProvider(t){const{payload:e}=await this.wire.sendAction("enable-native-window-integration-provider",{permissions:t});return e.data}registerUsage({data:t,type:e}){let n;try{const i=`${e}\0${JSON.stringify(t,D)}`;if(H(this,R,"f").has(i)||H(this,O,"f").has(i))return;H(this,O,"f").add(i),n=i}catch{console.debug(`[registerUsage] Failed to serialize 'data' for deduplication (type: "${e}"). Sending unconditionally.`)}H(this,W,"f").push({payload:{data:t,type:e},dedupKey:n}),H(this,j,"f")||(B(this,j,!0,"f"),queueMicrotask(()=>H(this,G,"m",N).call(this)))}async getPrinters(){const{payload:t}=await this.wire.sendAction("system-get-printers");return t.data}async updateProcessLoggingOptions(t){await this.wire.sendAction("system-update-process-logging-options",{options:t})}async getDomainSettings(){const{payload:{data:t}}=await this.wire.sendAction("get-domain-settings");return t}async setDomainSettings(t){await this.wire.sendAction("set-domain-settings",{domainSettings:t})}async getCurrentDomainSettings(t){return(await this.wire.sendAction("get-current-domain-settings",{identity:t})).payload.data}async resolveDomainSettings(t){return(await this.wire.sendAction("resolve-domain-settings",{url:t})).payload.data}async refreshExtensions(){const{payload:t}=await this.wire.sendAction("refresh-extensions");return t.data}async getInstalledExtensions(){const{payload:t}=await this.wire.sendAction("get-installed-extensions");return t.data}async serveAsset(t){return(await this.wire.sendAction("serve-asset",{options:t})).payload.data}async getThemePreferences(){return(await this.wire.sendAction("get-theme-preferences")).payload.data}async setThemePreferences(t){return(await this.wire.sendAction("set-theme-preferences",{preferences:t})).payload.data}async launchLogUploader(t){return(await this.wire.sendAction("launch-log-uploader",{options:t})).payload.data}async setThemePalette(t){return(await this.wire.sendAction("set-theme-palette",{themePalette:t})).payload.data}async getThemePalette(){const{payload:t}=await this.wire.sendAction("get-theme-palette");return t.data}}R=new WeakMap,O=new WeakMap,W=new WeakMap,j=new WeakMap,G=new WeakSet,N=function(){B(this,j,!1,"f");const t=H(this,W,"f");if(B(this,W,[],"f"),0===t.length)return;const e=t.map(({payload:t})=>t),n=t.map(({dedupKey:t})=>t),i=()=>{for(const t of n)void 0!==t&&H(this,O,"f").delete(t)};(1===e.length?this.wire.sendAction("register-usage",e[0]):this.wire.sendAction("register-usage-batch",{items:e})).then(()=>{for(const t of n)void 0!==t&&(H(this,O,"f").delete(t),H(this,R,"f").add(t))}).catch(t=>{i(),console.debug("[registerUsage] Failed to send usage data.",t)})};class U{constructor(){this.topicRefMap=new Map}incRefCount(t){const e=this.topicRefMap.get(t);let n;if(e){const i=e+1;n=i,this.topicRefMap.set(t,i)}else this.topicRefMap.set(t,1),n=1;return n}decRefCount(t){const e=this.topicRefMap.get(t);let n;if(e){const i=e-1;this.topicRefMap.set(t,i),n=i}else n=-1;return n}actOnFirst(t,e,n){return 1===this.incRefCount(t)?e():n()}actOnLast(t,e,n){return 0===this.decRefCount(t)?e():n()}}const z=t=>async(e,n,i)=>{const r=await t(e,n,i);return void 0===r?n:r};class _{constructor(t,e){this.providerIdentity=t,this.close=e}}class q{static defaultAction(t){throw new Error(`No action registered at target for ${t}`)}constructor(){this.subscriptions=new Map}async processAction(t,e,n){try{const i=this.subscriptions.get(t),r=i??((e,n)=>(this.defaultAction??q.defaultAction)(t,e,n)),s=this.preAction?await this.preAction(t,e,n):e,o=await r(s,n);return this.postAction?await this.postAction(t,o,n):o}catch(e){if(C.trimEndCallSites(e,/Channel.*processAction/),this.errorMiddleware)return this.errorMiddleware(t,e,n);throw e}}beforeAction(t){if(this.preAction)throw new Error("Already registered beforeAction middleware");this.preAction=z(t)}onError(t){if(this.errorMiddleware)throw new Error("Already registered error middleware");this.errorMiddleware=t}afterAction(t){if(this.postAction)throw new Error("Already registered afterAction middleware");this.postAction=z(t)}remove(t){this.subscriptions.delete(t)}setDefaultAction(t){if(this.defaultAction)throw new Error("default action can only be set once");this.defaultAction=t}register(t,e){if(this.subscriptions.has(t))throw new Error(`Subscription already registered for action: ${t}. Unsubscribe before adding new subscription`);return this.subscriptions.set(t,e),!0}}let J=class extends Error{constructor(t,e,n,i){super(t.message),this.action=e,this.dispatchPayload=n,this.name=this.constructor.name,"cause"in t&&t.cause instanceof Error&&(this.cause=t.cause),this.stack=C.prepareStackTrace(this,i)}};var Y,K,Z,Q=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)},X=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n};const tt=new Map;class et extends q{static closeChannelByEndpointId(t){const e=tt.get(t);e&&Q(e,Z,"f").call(e)}static handleProviderDisconnect(t){for(const e of tt.values())e.providerIdentity.channelId===t.channelId&&(e.disconnectListener(t),Q(e,Z,"f").call(e))}constructor(t,e,n){super(),Y.set(this,void 0),K.set(this,void 0),this.processAction=(t,e,n)=>super.processAction(t,e,n),Z.set(this,()=>{tt.delete(this.endpointId),Q(this,K,"f").close()}),X(this,Y,new _(t,e),"f"),this.disconnectListener=()=>{},this.endpointId=t.endpointId,X(this,K,n,"f"),tt.set(this.endpointId,this),n.receive(this.processAction)}get providerIdentity(){return Q(this,Y,"f").providerIdentity}async dispatch(t,e){if(Q(this,K,"f").isEndpointConnected(this.providerIdentity.channelId)){const n=C.getCallSite();return Q(this,K,"f").send(this.providerIdentity.channelId,t,e).catch(i=>{throw new J(i,t,e,n)})}throw new Error("The client you are trying to dispatch from is disconnected from the target provider.")}onDisconnection(t){this.disconnectListener=e=>{try{t(e)}catch(t){throw new Error(`Error while calling the onDisconnection callback: ${t.message}`)}finally{this.disconnectListener=()=>{}}}}async disconnect(){await this.sendDisconnectAction(),Q(this,Z,"f").call(this)}async sendDisconnectAction(){const t=Q(this,Y,"f");await t.close()}static async wireClose(t,e,n){const{channelName:i,uuid:r,name:s}=e;await t.sendAction("disconnect-from-channel",{channelName:i,uuid:r,name:s,endpointId:n})}}function nt(t,e){throw new Error(`Unsupported value: ${t}${e?`\n Supported values are: ${e.join("")}`:""}`)}Y=new WeakMap,K=new WeakMap,Z=new WeakMap;var it,rt,st,ot=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},at=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class ct{constructor(t,e,n,i){this.messageReceiver=e,this.endpointId=n,this.providerIdentity=i,it.set(this,void 0),rt.set(this,new Map),st.set(this,new Map),this.send=async(t,e,n)=>{const i=at(this,rt,"f").get(t);if(!i)throw new Error(`Could not locate routing info for endpoint ${t}`);const r={...i};r.isLocalEndpointId&&delete r.endpointId,delete r.isLocalEndpointId;const s=at(this,it,"f").sendAction("send-channel-message",{...r,providerIdentity:this.providerIdentity,action:e,payload:n});at(this,st,"f").get(t)?.add(s);return(await s.catch(t=>{if("cause"in t)throw t;throw new Error(t.message)}).finally(()=>{at(this,st,"f").get(t)?.delete(s)})).payload.data.result},this.close=async()=>{this.messageReceiver.removeEndpoint(this.providerIdentity.channelId,this.endpointId),[...at(this,rt,"f").keys()].forEach(t=>this.closeEndpoint(t)),ot(this,rt,new Map,"f")},ot(this,it,t,"f")}onEndpointDisconnect(t,e){}receive(t){this.messageReceiver.addEndpoint(t,this.providerIdentity.channelId,this.endpointId)}async closeEndpoint(t){const e=at(this,rt,"f").get(t);at(this,rt,"f").delete(t);const n=at(this,st,"f").get(t);n?.forEach(n=>{const i=`Channel connection with identity uuid: ${e?.uuid} / name: ${e?.name} / endpointId: ${t} no longer connected.`;n.cancel(new Error(i))})}isEndpointConnected(t){return at(this,rt,"f").has(t)}addEndpoint(t,e){at(this,rt,"f").set(t,e.endpointIdentity),at(this,st,"f").set(t,new Set)}isValidEndpointPayload(t){return"string"==typeof t?.endpointIdentity?.endpointId||"string"==typeof t?.endpointIdentity?.channelId}}it=new WeakMap,rt=new WeakMap,st=new WeakMap;const dt={version:5,minimumVersion:0,type:"classic"};function ht(t){const e={stack:t.stack,name:t.name,message:t.message,toString:()=>t.stack||t.toString()};return"cause"in t&&(e.cause=ht(t.cause)),e}var lt,pt,ut=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)},wt=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n};class yt{static isValidEndpointPayload(t){const e=t=>"object"==typeof t&&null!==t;return e(t)&&e(t.endpointIdentity)&&e(t.rtc)&&"string"==typeof t.endpointIdentity.endpointId}constructor({rtc:t,endpointIdentity:e}){this.responseMap=new Map,lt.set(this,null),pt.set(this,void 0),this.connectionStateChangeHandler=t=>{"connected"!==this.rtc.rtcClient.connectionState&&(this.rtc.rtcClient.removeEventListener("connectionstatechange",this.connectionStateChangeHandler),this.close(),ut(this,pt,"f")&&ut(this,pt,"f").call(this))},this.send=async(t,e)=>{const n=`message-${Math.random()}`,i=new Promise((t,e)=>{this.responseMap.set(n,{resolve:t,reject:e})});try{this.rtc.channels.request.send(JSON.stringify({action:t,payload:e,messageId:n}))}catch{this.disconnectOnSendFailure()}return i},this.close=()=>{this.responseMap.forEach(t=>t.reject("Connection has closed.")),this.responseMap=new Map,this.rtc.channels.request.close(),this.rtc.channels.response.close(),this.rtc.rtcClient.close()},this.rtc=t,this.endpointIdentity=e,this.rtc.channels.response.addEventListener("message",t=>{let{data:e}=t;t.data instanceof ArrayBuffer&&(e=(new TextDecoder).decode(t.data));const{messageId:n,payload:i,success:r,error:s}=JSON.parse(e),{resolve:o,reject:a}=this.responseMap.get(n)??{};o&&a?(this.responseMap.delete(n),r?o(i):a(s)):(console.log("Could not find id in responseMap."),console.log(t))}),this.rtc.channels.request.addEventListener("message",async t=>{let{data:n}=t;t.data instanceof ArrayBuffer&&(n=(new TextDecoder).decode(t.data));const{messageId:i,action:r,payload:s}=JSON.parse(n);if(ut(this,lt,"f"))try{const t=await ut(this,lt,"f").call(this,r,s,e);this.sendResponse(JSON.stringify({messageId:i,payload:t,success:!0}))}catch(t){"open"===this.rtc.channels.response.readyState&&this.sendResponse(JSON.stringify({messageId:i,error:ht(t),success:!1}))}else"open"===this.rtc.channels.response.readyState&&this.sendResponse(JSON.stringify({messageId:i,success:!1,error:"Connection not ready."}))}),this.rtc.rtcClient.addEventListener("connectionstatechange",this.connectionStateChangeHandler),Object.values(this.rtc.channels).forEach(t=>{t.onclose=t=>{[...this.responseMap.values()].forEach(t=>t.reject(new Error("RTCDataChannel closed unexpectedly, this is most commonly caused by message size. Note: RTC Channels have a message size limit of ~255kB."))),this.close(),ut(this,pt,"f")&&ut(this,pt,"f").call(this)}})}onDisconnect(t){if(ut(this,pt,"f"))throw new Error("RTCEndpoint disconnectListener cannot be set twice.");wt(this,pt,t,"f")}receive(t){if(ut(this,lt,"f"))throw new Error("You have already set a listener for this RTC Endpoint.");wt(this,lt,t,"f")}sendResponse(t){try{this.rtc.channels.response.send(t)}catch{this.disconnectOnSendFailure()}}disconnectOnSendFailure(){Object.values(this.rtc.channels).forEach(t=>{t.onclose=null}),[...this.responseMap.values()].forEach(t=>t.reject(new Error("RTCDataChannel closed unexpectedly, this is most commonly caused by message size. Note: RTC Channels have a message size limit of ~255kB."))),this.close(),ut(this,pt,"f")&&ut(this,pt,"f").call(this)}get connected(){return"connected"===this.rtc.rtcClient.connectionState}}lt=new WeakMap,pt=new WeakMap;var ft,gt,mt,vt=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)},Ct=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n};class It{constructor(t,e,n){this.EndpointType=t,this.StrategyName=n,ft.set(this,null),gt.set(this,new Map),mt.set(this,!0),this.send=async(t,e,n)=>this.getEndpointById(t).send(e,n),this.close=async()=>{vt(this,mt,"f")&&(vt(this,gt,"f").forEach(t=>t.close()),Ct(this,gt,new Map,"f")),Ct(this,mt,!1,"f")},this.isValidEndpointPayload=e}onEndpointDisconnect(t,e){this.getEndpointById(t).onDisconnect(e)}receive(t){if(vt(this,ft,"f"))throw new Error(`You have already set a listener for this ${this.StrategyName} Strategy`);Ct(this,ft,t,"f"),vt(this,gt,"f").forEach(t=>t.receive(vt(this,ft,"f")))}getEndpointById(t){const e=vt(this,gt,"f").get(t);if(!e)throw new Error(`Client with endpoint id ${t} is not connected`);return e}get connected(){return vt(this,mt,"f")}isEndpointConnected(t){return vt(this,gt,"f").has(t)}addEndpoint(t,e){if(!vt(this,mt,"f"))return void console.warn(`Adding endpoint to disconnected ${this.StrategyName} Strategy`);const n=new this.EndpointType(e);vt(this,ft,"f")&&n.receive(vt(this,ft,"f")),vt(this,gt,"f").set(t,n)}async closeEndpoint(t){vt(this,gt,"f").delete(t)}}ft=new WeakMap,gt=new WeakMap,mt=new WeakMap;class bt extends It{constructor(){super(yt,yt.isValidEndpointPayload,"RTC")}}const xt={version:2,minimumVersion:0,type:"rtc"};class At extends p{constructor(t){super(t,"channel"),this.ensureChannelOpened=t=>new Promise((e,n)=>{if("open"===t.readyState)e();else if("connecting"===t.readyState){const n=()=>{t.removeEventListener("open",n),e()};t.addEventListener("open",n)}else n(new Error("This Channel has already closed"))})}static createDataChannelPromise(t,e){let n;const i=new Promise(t=>{n=t}),r=i=>{const s=()=>{i.channel.removeEventListener("open",s),n(i.channel)};i.channel.label===t&&(i.channel.addEventListener("open",s),e.removeEventListener("datachannel",r))};return e.addEventListener("datachannel",r),i}async listenForProviderIce(t,e){await this.on(this.createProviderEventName(t),e,{timestamp:Date.now()})}async raiseProviderIce(t,e){await this.wire.environment.raiseEvent(this.createRouteString(this.createProviderEventName(t)),e)}async listenForClientIce(t,e){await this.on(this.createClientEventName(t),e,{timestamp:Date.now()})}async raiseClientIce(t,e){await this.wire.environment.raiseEvent(this.createRouteString(this.createClientEventName(t)),e)}cleanupIceListeners(t){this.removeAllListeners(this.createClientEventName(t)),this.removeAllListeners(this.createProviderEventName(t))}createClientEventName(t){return`ice-client-${t}`}createProviderEventName(t){return`ice-provider-${t}`}createRouteString(t){return`channel/${t}`}createRtcPeer(){return this.wire.environment.getRtcPeer()}async startClientOffer(){const t=Math.random().toString(),e=this.createRtcPeer();e.addEventListener("icecandidate",async e=>{e.candidate&&await this.raiseClientIce(t,{candidate:e.candidate?.toJSON()})}),await this.listenForProviderIce(t,async t=>{await e.addIceCandidate(t.candidate)});const n={request:e.createDataChannel("request"),response:e.createDataChannel("response")},i=await e.createOffer();await e.setLocalDescription(i);const r=Promise.all([n.request,n.response].map(this.ensureChannelOpened)).then(()=>{});return{rtcClient:e,channels:n,offer:i,rtcConnectionId:t,channelsOpened:r}}async finishClientOffer(t,e,n){return await t.setRemoteDescription(e),await n,!0}async createProviderAnswer(t,e){const n=this.createRtcPeer(),i=At.createDataChannelPromise("request",n),r=At.createDataChannelPromise("response",n);n.addEventListener("icecandidate",async e=>{e.candidate&&await this.raiseProviderIce(t,{candidate:e.candidate?.toJSON()})}),await this.listenForClientIce(t,async t=>{await n.addIceCandidate(t.candidate)}),await n.setRemoteDescription(e);const s=await n.createAnswer();await n.setLocalDescription(s);const o=Promise.all([i,r]).then(([e,n])=>(this.cleanupIceListeners(t),{request:e,response:n}));return{rtcClient:n,answer:s,channels:o}}}function Et(t){return[...t.split(".").reverse().entries()].reduce((t,[e,n])=>t+ +n*1e4**e,0)}function Pt(t,e){const n=function(t){return t.split("/")[0]}(t);return function(t,e){return Et(t)>=Et(e)}(n,e)}var Mt,St,kt,Tt,Lt,$t,Ft=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)},Gt=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n};class Rt extends q{get connections(){return[...Ft(this,St,"f")]}static handleClientDisconnection(t,e){if(e.endpointId)Ft(t,Lt,"f").call(t,{endpointId:e.endpointId});else{t.connections.filter(t=>t.uuid===e.uuid&&t.name===e.name).forEach(Ft(t,Lt,"f"))}t.disconnectListener(e)}static setProviderRemoval(t,e){Mt.removalMap.set(t,e)}constructor(t,e,n){super(),St.set(this,void 0),kt.set(this,void 0),Tt.set(this,void 0),Lt.set(this,t=>{const e=this.connections.filter(e=>e.endpointId!==t.endpointId);Ft(this,Tt,"f").closeEndpoint(t.endpointId),Gt(this,St,e,"f")}),this.processAction=async(t,e,n)=>(Mt.clientIsMultiRuntime(n)&&!Pt(n.runtimeUuid,"18.87.56.0")?this.handleMultiRuntimeLegacyClient(n):this.checkForClientConnection(n),super.processAction(t,e,n)),$t.set(this,()=>{Ft(this,Tt,"f").close();const t=Mt.removalMap.get(this);t&&t()}),Gt(this,kt,new _(t,e),"f"),this.connectListener=()=>{},this.disconnectListener=()=>{},Gt(this,St,[],"f"),Gt(this,Tt,n,"f"),n.receive(this.processAction)}dispatch(t,e,n){const i=t.endpointId??this.getEndpointIdForOpenFinId(t,e);if(i&&Ft(this,Tt,"f").isEndpointConnected(i)){const t=C.getCallSite();return Ft(this,Tt,"f").send(i,e,n).catch(i=>{throw new J(i,e,n,t)})}return Promise.reject(new Error(`Client connection with identity uuid: ${t.uuid} / name: ${t.name} / endpointId: ${i} no longer connected.`))}async processConnection(t,e){return Ft(this,St,"f").push(t),this.connectListener(t,e)}publish(t,e){return this.connections.map(n=>Ft(this,Tt,"f").send(n.endpointId,t,e))}onConnection(t){this.connectListener=t}onDisconnection(t){this.disconnectListener=e=>{t(e)}}async destroy(){const t=Ft(this,kt,"f");Gt(this,St,[],"f"),await t.close(),Ft(this,$t,"f").call(this)}async getAllClientInfo(){return this.connections.map(t=>{const{uuid:e,name:n,endpointId:i,entityType:r,connectionUrl:s}=t;return{uuid:e,name:n,endpointId:i,entityType:r,connectionUrl:s}})}checkForClientConnection(t){if(!this.isClientConnected(t))throw new Error(`This action was sent from a client that is not connected to the provider.\n Client Identity: {uuid: ${t.uuid}, name: ${t.name}, endpointId: ${t.endpointId}}`)}isClientConnected(t){return Mt.clientIdentityIncludesEndpointId(t)?this.connections.some(e=>e.endpointId===t.endpointId&&e.uuid===t.uuid&&e.name===t.name):this.isLegacyClientConnected(t)}isLegacyClientConnected(t){return this.connections.some(e=>e.uuid===t.uuid&&e.name===t.name)}handleMultiRuntimeLegacyClient(t){if(!this.isLegacyClientConnected(t))throw new Error(`This action was sent from a client that is not connected to the provider. Client Identity:\n {uuid: ${t.uuid}, name: ${t.name}, endpointId: ${t.endpointId}}`)}getEndpointIdForOpenFinId(t,e){const n=this.connections.filter(e=>e.name===t.name&&e.uuid===t.uuid);if(n.length>=2){const n=Ft(this,kt,"f"),{uuid:i,name:r}=t,s=n?.providerIdentity.uuid,o=n?.providerIdentity.name;console.warn(`WARNING: Dispatch call may have unintended results. The "to" argument of your dispatch call is missing the\n "endpointId" parameter. The identity you are dispatching to ({uuid: ${i}, name: ${r}})\n has multiple channelClients for this channel. Your dispatched action: (${e}) from the provider:\n ({uuid: ${s}, name: ${o}}) will only be processed by the most recently-created client.`)}return n.pop()?.endpointId}static clientIdentityIncludesEndpointId(t){return void 0!==t.endpointId}static clientIsMultiRuntime(t){return void 0!==t.runtimeUuid}static async wireClose(t,e){await t.sendAction("destroy-channel",{channelName:e})}}Mt=Rt,St=new WeakMap,kt=new WeakMap,Tt=new WeakMap,Lt=new WeakMap,$t=new WeakMap,Rt.removalMap=new WeakMap;class Ot extends l{constructor(t){super(t),this.onmessage=t=>"process-channel-message"===t.action&&(this.processChannelMessage(t),!0),this.endpointMap=new Map,this.latestEndpointIdByChannelId=new Map,t.registerMessageHandler(this.onmessage.bind(this))}async processChannelMessage(t){const{senderIdentity:e,providerIdentity:n,action:i,ackToSender:r,payload:s,intendedTargetIdentity:o}=t.payload,a=o.channelId??o.endpointId??this.latestEndpointIdByChannelId.get(n.channelId),c=this.endpointMap.get(a);if(!c)return r.payload.success=!1,r.payload.reason=`Client connection with identity uuid: ${this.wire.me.uuid} / name: ${this.wire.me.name} / endpointId: ${a} no longer connected.`,r.payload.error=ht(new Error(r.payload.reason)),this.wire.sendRaw(r);try{const t=await c(i,s,e);return r.payload.payload=r.payload.payload||{},r.payload.payload.result=t,this.wire.sendRaw(r)}catch(t){return r.payload.success=!1,r.payload.reason=t.message,r.payload.error=ht(t),this.wire.sendRaw(r)}}addEndpoint(t,e,n){this.endpointMap.set(n,t),e!==n&&this.latestEndpointIdByChannelId.set(e,n)}removeEndpoint(t,e){this.endpointMap.delete(e),this.latestEndpointIdByChannelId.get(t)===e&&this.latestEndpointIdByChannelId.delete(t)}checkForPreviousClientConnection(t){const e=this.latestEndpointIdByChannelId.get(t);e&&(et.closeChannelByEndpointId(e),console.warn("You have created a second connection to an older provider. First connection has been removed from the clientMap"),console.warn("If the provider calls publish(), you may receive multiple messages."))}}class Wt{constructor(t){this.ProtocolsInPreferenceOrder=t,this.DefaultClientProtocols=["classic"],this.DefaultProviderProtocols=["classic"],this.getClientProtocols=t=>{const e=t?this.ProtocolsInPreferenceOrder.filter(e=>t.includes(e)):this.DefaultClientProtocols;if(!e.length)throw new Error(`No valid protocols were passed in. Accepted values are: ${this.ProtocolsInPreferenceOrder.join(", ")}.`);return e},this.getProviderProtocols=t=>{const e=t?this.ProtocolsInPreferenceOrder.filter(e=>t.includes(e)):this.DefaultProviderProtocols;if(!e.length)throw new Error(`No valid protocols were passed in. Accepted values are: ${this.ProtocolsInPreferenceOrder.join(", ")}.`);return e},this.getCompatibleProtocols=(t,e)=>e.supportedProtocols.filter(e=>t.some(t=>t.type===e.type&&e.version>=t.minimumVersion&&t.version>=(e.minimumVersion??0))).slice(0,e.maxProtocols)}}class jt{static combine(t,e){return new jt(t,e)}constructor(t,e){this.primary=t,this.secondary=e}onEndpointDisconnect(t,e){this.primary.onEndpointDisconnect(t,()=>{this.secondary.isEndpointConnected(t)||e()}),this.secondary.onEndpointDisconnect(t,()=>{this.primary.isEndpointConnected(t)||e()})}isValidEndpointPayload(t){return this.primary.isValidEndpointPayload(t)||this.secondary.isValidEndpointPayload(t)}async closeEndpoint(t){await this.primary.closeEndpoint(t),await this.secondary.closeEndpoint(t)}isEndpointConnected(t){return this.primary.isEndpointConnected(t)||this.secondary.isEndpointConnected(t)}async addEndpoint(t,e){this.primary.isValidEndpointPayload(e)&&await this.primary.addEndpoint(t,e),this.secondary.isValidEndpointPayload(e)&&await this.secondary.addEndpoint(t,e)}receive(t){this.primary.receive(t),this.secondary.receive(t)}send(t,e,n){return this.primary.isEndpointConnected(t)?this.primary.send(t,e,n):this.secondary.send(t,e,n)}async close(){await Promise.all([this.primary.close(),this.secondary.close()])}}var Nt,Ht,Bt=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},Dt=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class Vt extends l{static getProtocolOptionsFromStrings(t){return t.map(t=>{switch(t){case"rtc":return xt;case"classic":return dt;default:return nt(t,["rtc","classic"])}})}constructor(t){super(t),Nt.set(this,void 0),Ht.set(this,void 0),this.removeChannelFromProviderMap=t=>{const e=this.providerMap.get(t);if(e){const{channelName:n}=e.providerIdentity;this.providerChannelIdByName.get(n)===t&&this.providerChannelIdByName.delete(n)}this.providerMap.delete(t)},this.onmessage=t=>"process-channel-connection"===t.action&&(this.processChannelConnection(t),!0),this.providerMap=new Map,this.providerChannelIdByName=new Map,this.protocolManager=new Wt("node"===this.wire.environment.type?["classic"]:["rtc","classic"]),Bt(this,Nt,new Ot(t),"f"),Bt(this,Ht,new At(t),"f"),t.registerMessageHandler(this.onmessage.bind(this))}createProvider(t,e){const n=Object.assign(this.wire.environment.getDefaultChannelOptions().create,t||{}),i=this.protocolManager.getProviderProtocols(n?.protocols),r=i.map(t=>{switch(t){case"rtc":return new bt;case"classic":return new ct(this.wire,Dt(this,Nt,"f"),e.channelId,e);default:return nt(t,["rtc","classic"])}});let s;if(2===r.length){const[t,e]=r;s=jt.combine(t,e)}else{if(1!==r.length)throw new Error("failed to combine strategies");[s]=r}const o=new Rt(e,()=>Rt.wireClose(this.wire,e.channelName),s),a=e.channelId;return this.providerMap.set(a,{providerIdentity:e,provider:o,strategy:s,supportedProtocols:Vt.getProtocolOptionsFromStrings(i)}),this.providerChannelIdByName.set(e.channelName,a),Rt.setProviderRemoval(o,this.removeChannelFromProviderMap.bind(this)),o}async createClientOffer(t){const e=this.protocolManager.getClientProtocols(t?.protocols);let n;return{offer:{supportedProtocols:await Promise.all(e.map(async t=>{switch(t){case"rtc":{const{rtcClient:t,channels:e,offer:i,rtcConnectionId:r,channelsOpened:s}=await Dt(this,Ht,"f").startClientOffer();return n={rtcClient:t,channels:e,channelsOpened:s},{type:"rtc",version:xt.version,payload:{offer:i,rtcConnectionId:r}}}case"classic":return{type:"classic",version:dt.version};default:return nt(t,["rtc","classic"])}})),maxProtocols:2},rtc:n}}async createClientStrategy(t,e){e.endpointId||(e.endpointId=this.wire.environment.getNextMessageId(),Dt(this,Nt,"f").checkForPreviousClientConnection(e.channelId));const n=e.answer??{supportedProtocols:[{type:"classic",version:1}]},i=(await Promise.all(n.supportedProtocols.map(async n=>"rtc"===n.type&&t?(await Dt(this,Ht,"f").finishClientOffer(t.rtcClient,n.payload.answer,t.channelsOpened),new bt):"classic"===n.type?new ct(this.wire,Dt(this,Nt,"f"),e.endpointId,e):null))).filter(t=>null!==t);let r;if(t&&!i.some(t=>t instanceof bt)&&t&&t.rtcClient.close(),i.length>=2)r=jt.combine(i[0],i[1]);else{if(!i.length)throw new Error("No compatible protocols");[r]=i}const s={endpointIdentity:e,rtc:t};return r.addEndpoint(e.channelId,s),r}handleClientDisconnection(t){const e=t.channelId??this.providerChannelIdByName.get(t.channelName??"");if(!e)return;const n=this.providerMap.get(e);n&&Rt.handleClientDisconnection(n.provider,t)}async processChannelConnection(t){const{clientIdentity:e,providerIdentity:n,ackToSender:i,payload:r,offer:s}=t.payload;e.endpointId?e.isLocalEndpointId=!1:(e.endpointId=this.wire.environment.getNextMessageId(),e.isLocalEndpointId=!0);const o=n.channelId,a=this.providerMap.get(o);if(!a)return i.payload.success=!1,i.payload.reason=`Channel "${n.channelName}" has been destroyed.`,this.wire.sendRaw(i);const{provider:c,strategy:d,supportedProtocols:h}=a;try{if(!(c instanceof Rt))throw Error("Cannot connect to a channel client");const t=s??{supportedProtocols:[{type:"classic",version:1}],maxProtocols:1},n=this.protocolManager.getCompatibleProtocols(h,t);if(!n.length)throw new Error("This provider does not support any of the offered protocols.");const o=await c.processConnection(e,r);i.payload.payload=i.payload.payload||{};let a={supportedProtocols:[],endpointPayloadPromise:Promise.resolve({endpointIdentity:e})};return a=await n.reduce(async(t,e)=>{const n=await t;if("rtc"===e.type){const{answer:t,rtcClient:i,channels:r}=await Dt(this,Ht,"f").createProviderAnswer(e.payload.rtcConnectionId,e.payload.offer);n.supportedProtocols.push({type:"rtc",version:xt.version,payload:{answer:t}}),n.endpointPayloadPromise=n.endpointPayloadPromise.then(t=>r.then(e=>({...t,rtc:{rtcClient:i,channels:e}})))}else n.supportedProtocols.push({type:"classic",version:dt.version});return n},Promise.resolve(a)),a.endpointPayloadPromise.then(t=>d.addEndpoint(e.endpointId,t)),i.payload.payload.result=o,i.payload.payload.answer=a,this.wire.sendRaw(i)}catch(t){return i.payload.success=!1,i.payload.reason=t.message,this.wire.sendRaw(i)}}}Nt=new WeakMap,Ht=new WeakMap;var Ut,zt,_t,qt,Jt=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},Yt=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};function Kt(t){const e=Math.floor(t/10),n=Math.min(3e4,500*2**e);return new Promise(t=>{setTimeout(()=>{t(!1)},n)})}class Zt extends p{constructor(e){super(e,"channel"),Ut.set(this,void 0),zt.set(this,new t),_t.set(this,new E(async()=>{await this.on("client-disconnected",t=>{Yt(this,Ut,"f").handleClientDisconnection(t)})})),qt.set(this,new E(async()=>{await Promise.all([Yt(this,_t,"f").getValue(),this.on("disconnected",t=>{et.handleProviderDisconnect(t)}),this.on("connected",(...t)=>{Yt(this,zt,"f").emit("connected",...t)})]).catch(()=>new Error("error setting up channel connection listeners"))})),Jt(this,Ut,new Vt(e),"f")}async getAllChannels(){return this.wire.sendAction("get-all-channels").then(({payload:t})=>t.data)}async onChannelConnect(t){await this.on("connected",t)}async onChannelDisconnect(t){await this.on("disconnected",t)}async safeConnect(t,e,n){const i={count:0};do{let r=()=>{};const s=new Promise(e=>{r=n=>{t===n.channelName&&e(!0)},Yt(this,zt,"f").on("connected",r)});try{if(i.count>0){i.gotConnectedEvent=await Promise.race([Kt(i.count),s]);const e=await this.wire.sendAction("connect-to-channel",{...n,retryInfo:i});return console.log(`Successfully connected to channelName: ${t}`),e.payload.data}const e=this.wire.sendAction("connect-to-channel",n);i.originalMessageId=e.messageId;return(await e).payload.data}catch(n){if(!n.message.includes("internal-nack"))throw n;e&&0===i.count&&console.warn(`No channel found for channelName: ${t}. Waiting for connection...`)}finally{i.count+=1,Yt(this,zt,"f").removeListener("connected",r)}}while(e);throw new Error(`No channel found for channelName: ${t}.`)}async connect(t,e={}){if(await Yt(this,qt,"f").getValue(),!t||"string"!=typeof t)throw new Error("Please provide a channelName string to connect to a channel.");const n={wait:!0,...this.wire.environment.getDefaultChannelOptions().connect,...e},{offer:i,rtc:r}=await Yt(this,Ut,"f").createClientOffer(n);let s;(this.fin.me.isFrame||this.fin.me.isView||this.fin.me.isWindow)&&(s=(await this.fin.me.getInfo()).url);const o={channelName:t,...n,offer:i,connectionUrl:s},a=await this.safeConnect(t,n.wait,o),c=await Yt(this,Ut,"f").createClientStrategy(r,a),d=new et(a,()=>et.wireClose(this.wire,a,a.endpointId),c);return c.onEndpointDisconnect(a.channelId,async()=>{try{await d.sendDisconnectAction()}catch(t){console.warn(`Something went wrong during disconnect for client with uuid: ${a.uuid} / name: ${a.name} / endpointId: ${a.endpointId}.`)}finally{et.handleProviderDisconnect(a)}}),d}async create(t,e){if(await Yt(this,_t,"f").getValue(),!t)throw new Error("Please provide a channelName to create a channel");const{payload:{data:n}}=await this.wire.sendAction("create-channel",{channelName:t});return Yt(this,Ut,"f").createProvider(e,n)}}Ut=new WeakMap,zt=new WeakMap,_t=new WeakMap,qt=new WeakMap;class Qt extends l{constructor(e){super(e),this.events={subscriberAdded:"subscriber-added",subscriberRemoved:"subscriber-removed"},this.refCounter=new U,this.Channel=new Zt(e),this.emitter=new t,e.registerMessageHandler(this.onmessage.bind(this)),this.on=this.emitter.on.bind(this.emitter),this.removeAllListeners=this.emitter.removeAllListeners.bind(this.emitter)}async publish(t,e){await this.wire.sendAction("publish-message",{topic:t,message:e,sourceWindowName:this.me.name})}async send(t,e,n){const i=I(t);if(i)throw new Error(i);await this.wire.sendAction("send-message",{destinationUuid:t.uuid,destinationWindowName:t.name,topic:e,message:n,sourceWindowName:this.me.name})}subscribe(t,e,n){const i=this.createSubscriptionKey(t.uuid,t.name||"*",e);return this.emitter.on(i,n),this.refCounter.actOnFirst(i,async()=>{await this.wire.sendAction("subscribe",{sourceUuid:t.uuid,sourceWindowName:t.name||"*",topic:e,destinationWindowName:this.me.name})},()=>Promise.resolve())}unsubscribe(t,e,n){const i=t.name||"*",r=this.createSubscriptionKey(t.uuid,i,e);return this.emitter.removeListener(r,n),this.refCounter.actOnLast(r,async()=>{await this.wire.sendAction("unsubscribe",{sourceUuid:t.uuid,sourceWindowName:i,topic:e,destinationWindowName:this.me.name})},()=>new Promise(t=>t).then(()=>{}))}processMessage(t){const{payload:{message:e,sourceWindowName:n,sourceUuid:i,topic:r}}=t,s=[this.createSubscriptionKey(i,n,r),this.createSubscriptionKey(i,"*",r),this.createSubscriptionKey("*","*",r)],o={uuid:i,name:n};s.forEach(t=>{this.emitter.emit(t,e,o)})}emitSubscriverEvent(t,e){const{payload:{targetName:n,uuid:i,topic:r}}=e,s={name:n,uuid:i,topic:r};this.emitter.emit(t,s)}createSubscriptionKey(t,e,n){const i=e||"*";if(!(t&&i&&n))throw new Error("Missing uuid, name, or topic string");return function(...t){return t.map(t=>btoa(t)).join("/")}(t,i,n)}onmessage(t){const{action:e}=t;switch(e){case"process-message":this.processMessage(t);break;case this.events.subscriberAdded:this.emitSubscriverEvent(this.events.subscriberAdded,t);break;case this.events.subscriberRemoved:this.emitSubscriverEvent(this.events.subscriberRemoved,t)}return!0}}class Xt extends l{async writeText(t){await this.wire.sendAction("clipboard-write-text",t)}async readText(t){const{payload:e}=await this.wire.sendAction("clipboard-read-text",{type:t});return e.data}async writeImage(t){await this.wire.sendAction("clipboard-write-image",t)}async readImage(t={format:"dataURL"}){const{payload:e}=await this.wire.sendAction("clipboard-read-image",t);return e.data}async writeHtml(t){await this.wire.sendAction("clipboard-write-html",t)}async readHtml(t){const{payload:e}=await this.wire.sendAction("clipboard-read-html",{type:t});return e.data}async writeRtf(t){await this.wire.sendAction("clipboard-write-rtf",t)}async readRtf(t){const{payload:e}=await this.wire.sendAction("clipboard-read-rtf",{type:t});return e.data}async write(t){await this.wire.sendAction("clipboard-write",t)}async getAvailableFormats(t){const{payload:e}=await this.wire.sendAction("clipboard-read-formats",{type:t});return e.data}}class te extends p{constructor(t,e){super(t,"external-application",e.uuid),this.identity=e}getInfo(){return this.wire.sendAction("get-external-application-info",this.identity).then(({payload:t})=>t.data)}}class ee extends l{wrap(t){return this.wire.recordAnalytic("external-application-wrap"),Promise.resolve(new te(this.wire,{uuid:t}))}wrapSync(t){return this.wire.recordAnalytic("external-application-wrap-sync"),new te(this.wire,{uuid:t})}}class ne extends p{constructor(t,e){super(t,"frame",e.uuid,e.name),this.identity=e}getInfo(){return this.wire.sendAction("get-frame-info",this.identity).then(({payload:t})=>t.data)}getParentWindow(){return this.wire.sendAction("get-parent-window",this.identity).then(({payload:t})=>t.data)}}class ie extends l{async wrap(t){this.wire.recordAnalytic("frame-wrap");const e=I(t);if(e)throw new Error(e);return new ne(this.wire,t)}wrapSync(t){this.wire.recordAnalytic("frame-wrap-sync");const e=I(t);if(e)throw new Error(e);return new ne(this.wire,t)}getCurrent(){return this.wire.recordAnalytic("frame-get-current"),Promise.resolve(new ne(this.wire,this.wire.environment.getCurrentEntityIdentity()))}getCurrentSync(){return this.wire.recordAnalytic("frame-get-current-sync"),new ne(this.wire,this.wire.environment.getCurrentEntityIdentity())}}class re extends p{constructor(t){super(t,"global-hotkey")}async register(t,e){await this.on(t,e),await this.wire.sendAction("global-hotkey-register",{hotkey:t})}async unregister(t){await this.removeAllListeners(t),await this.wire.sendAction("global-hotkey-unregister",{hotkey:t})}async unregisterAll(){await Promise.all(this.eventNames().filter(t=>!("registered"===t||"unregistered"===t)).map(t=>this.removeAllListeners(t))),await this.wire.sendAction("global-hotkey-unregister-all",{})}async isRegistered(t){const{payload:{data:e}}=await this.wire.sendAction("global-hotkey-is-registered",{hotkey:t});return e}}var se,oe,ae,ce=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},de=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class he extends p{constructor(t,e,n=`custom-frame-${e.uuid}`){super(t,"application",e.uuid),oe.set(this,void 0),this.getClient=(t=this.identity)=>{if(t.uuid!==this.identity.uuid)return new se(this.wire,t).getClient();if(this.wire.sendAction("platform-get-client",this.identity).catch(t=>{}),!se.clientMap.has(de(this,oe,"f"))){const t=de(this,ae,"f").call(this);se.clientMap.set(de(this,oe,"f"),t)}return se.clientMap.get(de(this,oe,"f"))},ae.set(this,async()=>{try{const t=await this._channel.connect(de(this,oe,"f"),{wait:!1});return t.onDisconnection(()=>{se.clientMap.delete(de(this,oe,"f"))}),t}catch(t){throw se.clientMap.delete(de(this,oe,"f")),new Error("The targeted Platform is not currently running. Listen for application-started event for the given Uuid.")}}),this.launchLegacyManifest=this.launchContentManifest;const i=I(e);if(i)throw new Error(i);ce(this,oe,n,"f"),this._channel=this.fin.InterApplicationBus.Channel,this.identity={uuid:e.uuid},this.Layout=this.fin.Platform.Layout,this.Application=this.fin.Application.wrapSync(this.identity)}async createView(t,e,n){this.wire.sendAction("platform-create-view",this.identity).catch(t=>{});const i=await this.getClient(),r=await i.dispatch("create-view",{target:e,opts:t,targetView:n});if(!r||I(r.identity))throw new Error(`When overwriting the createView call, please return an object that has a valid 'identity' property: ${JSON.stringify(r)}`);return this.fin.View.wrapSync(r.identity)}async createWindow(t){this.wire.sendAction("platform-create-window",this.identity).catch(t=>{});const e=await this.getClient();t.reason||(t.reason="api-call");const n=await e.dispatch("create-view-container",t);if(!n||I(n.identity))throw new Error(`When overwriting the createWindow call, please return an object that has a valid 'identity' property: ${JSON.stringify(n)}`);const{identity:i}=n,r=this.fin.Window.wrapSync(i);return r.name=i.name,r.uuid=i.uuid,r}async quit(){this.wire.sendAction("platform-quit",this.identity).catch(t=>{});return(await this.getClient()).dispatch("quit")}async closeView(t){this.wire.sendAction("platform-close-view",this.identity).catch(t=>{});const e=await this.getClient();await e.dispatch("close-view",{view:t})}async reparentView(t,e){console.warn("Platform.reparentView has been deprecated, please use Platform.createView"),this.wire.sendAction("platform-reparent-view",this.identity).catch(t=>{});const n={...t,uuid:t.uuid??this.identity.uuid},i=await this.fin.View.wrap(n),r=await i.getOptions();return this.createView(r,e)}async getSnapshot(){this.wire.sendAction("platform-get-snapshot",this.identity).catch(t=>{});return(await this.getClient()).dispatch("get-snapshot")}async getViewSnapshot(t){return(await this.getClient()).dispatch("get-view-snapshot",{viewIdentity:t})}async applySnapshot(t,e){this.wire.sendAction("platform-apply-snapshot",this.identity).catch(t=>{});const n="Requested snapshot must be a valid Snapshot object, or a url or filepath to such an object.";let i;if("string"==typeof t)try{i=(await this._channel.wire.sendAction("get-application-manifest",{manifestUrl:t})).payload.data}catch(t){throw new Error(`${n}: ${t}`)}else i=t;if(!i.windows)throw new Error(n);const r=await this.getClient();return await r.dispatch("apply-snapshot",{snapshot:i,options:e}),this}async fetchManifest(t){return(await this.getClient()).dispatch("platform-fetch-manifest",{manifestUrl:t})}async launchContentManifest(t){this.wire.sendAction("platform-launch-content-manifest",this.identity).catch(()=>{});const e=await this.getClient(),n=await this.fetchManifest(t);return e.dispatch("launch-into-platform",{manifest:n,manifestUrl:t}),this}async setWindowContext(t={},e){if(this.wire.sendAction("platform-set-window-context",this.identity).catch(t=>{}),!t)throw new Error("Please provide a serializable object or string to set the context.");const n=await this.getClient(),{entityType:i}=e?await this.fin.System.getEntityInfo(e.uuid,e.name):this.fin.me;await n.dispatch("set-window-context",{context:t,entityType:i,target:e||{uuid:this.fin.me.uuid,name:this.fin.me.name}})}async getWindowContext(t){this.wire.sendAction("platform-get-window-context",this.identity).catch(t=>{});const e=await this.getClient(),{entityType:n}=t?await this.fin.System.getEntityInfo(t.uuid,t.name):this.fin.me;return e.dispatch("get-window-context",{target:t||{uuid:this.fin.me.uuid,name:this.fin.me.name},entityType:n})}async closeWindow(t,e={skipBeforeUnload:!1}){this.wire.sendAction("platform-close-window",this.identity).catch(t=>{});return(await this.getClient()).dispatch("close-window",{windowId:t,options:e})}}se=he,oe=new WeakMap,ae=new WeakMap,he.clientMap=new Map;class le{constructor(t){this.strategy=t,this.consume=async t=>(await this.strategy.getExposedFunctions(t)).reduce((e,n)=>({...e,[n.key]:this.strategy.createFunction(n,t)}),{})}}class pe{constructor(t){this.channel=t,this.getExposedFunctions=async t=>{const{id:e}=t,{props:n}=await this.channel.dispatch(`api-meta:${e}`);return n},this.createFunction=t=>(...e)=>{const{action:n}=t.options;return this.channel.dispatch(n,{args:e})}}}const ue=["no longer connected","RTCDataChannel closed unexpectedly","The client you are trying to dispatch from is disconnected from the target provider"],we=async(t,e)=>{t.register(`relay:${e}`,({action:e,target:n,payload:i})=>t.dispatch(n,e,i)),await Promise.resolve()},ye=(t,e,n,i)=>async(r,s)=>{try{return await t.dispatch(`relay:${n}`,{action:r,payload:s,target:e})}catch(t){if(o=t.message,ue.some(t=>o.includes(t))&&i)throw new Error(i);throw t}var o};var fe,ge,me,ve,Ce=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},Ie=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class be{constructor(t,e){ge.set(this,void 0),this.isRoot=()=>Ie(this,ge,"f").isRoot(this.entityId),this.exists=()=>Ie(this,ge,"f").exists(this.entityId),this.getParent=async()=>{const t=await Ie(this,ge,"f").getParent(this.entityId);if(t)return fe.getEntity(t,Ie(this,ge,"f"))},this.createAdjacentStack=async(t,e)=>{const n=await Ie(this,ge,"f").createAdjacentStack(this.entityId,t,e);return fe.getEntity({entityId:n,type:"stack"},Ie(this,ge,"f"))},this.getAdjacentStacks=async t=>(await Ie(this,ge,"f").getAdjacentStacks({targetId:this.entityId,edge:t})).map(t=>fe.getEntity({type:"stack",entityId:t.entityId},Ie(this,ge,"f"))),Ce(this,ge,t,"f"),this.entityId=e}}fe=be,ge=new WeakMap,be.newLayoutEntitiesClient=async(t,e,n)=>{const i=ye(t,n,"layout-relay","You are trying to interact with a layout component on a window that does not exist or has been destroyed.");return new le(new pe({dispatch:i})).consume({id:e})},be.getEntity=(t,e)=>{const{entityId:n,type:i}=t;switch(i){case"column":case"row":return new Ae(e,n,i);case"stack":return new xe(e,n);default:throw new Error(`Unrecognised Layout Entity encountered ('${JSON.stringify(t)})`)}};class xe extends be{constructor(t,e){super(t,e),me.set(this,void 0),this.type="stack",this.getViews=()=>Ie(this,me,"f").getStackViews(this.entityId),this.addView=async(t,e={index:0})=>Ie(this,me,"f").addViewToStack(this.entityId,t,e),this.removeView=async t=>{await Ie(this,me,"f").removeViewFromStack(this.entityId,t)},this.setActiveView=async t=>{await Ie(this,me,"f").setStackActiveView(this.entityId,t)},Ce(this,me,t,"f")}}me=new WeakMap;class Ae extends be{constructor(t,e,n){super(t,e),ve.set(this,void 0),this.getContent=async()=>(await Ie(this,ve,"f").getContent(this.entityId)).map(t=>be.getEntity(t,Ie(this,ve,"f"))),Ce(this,ve,t,"f"),this.type=n}}ve=new WeakMap;const Ee="layout-entities";var Pe,Me,Se,ke=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class Te extends l{static getClient(t){return ke(t,Me,"f").getValue()}constructor(t,e){super(e),Pe.add(this),Me.set(this,new A(async()=>be.newLayoutEntitiesClient(await this.platform.getClient(),Ee,this.identity))),this.replace=async t=>{this.wire.sendAction("layout-replace").catch(t=>{});const e=await this.platform.getClient();await e.dispatch("replace-layout",{target:this.identity,opts:{layout:t}})},this.replaceView=async(t,e)=>{this.wire.sendAction("layout-replace-view").catch(t=>{});const n=await this.platform.getClient();await n.dispatch("replace-view",{target:this.identity,opts:{viewToReplace:t,newView:e}})},this.applyPreset=async t=>{this.wire.sendAction("layout-apply-preset").catch(t=>{});const e=await this.platform.getClient(),{presetType:n}=t;if(!n||!function(t){switch(t){case"columns":case"grid":case"rows":case"tabs":return!0;default:return!1}}(n))throw new Error("Cannot apply preset layout, please include an applicable presetType property in the PresetLayoutOptions.");await e.dispatch("apply-preset-layout",{target:this.identity,opts:{presetType:n}})};const n=I(t);if(n)throw new Error(n);this.identity=t,this.platform=this.fin.Platform.wrapSync({uuid:t.uuid}),t.uuid===this.fin.me.uuid&&t.name===this.fin.me.name&&(this.init=this.fin.Platform.Layout.init)}async getConfig(){this.wire.sendAction("layout-get-config").catch(t=>{});return(await this.platform.getClient()).dispatch("get-frame-snapshot",{target:this.identity})}async getCurrentViews(){this.wire.sendAction("layout-get-views").catch(t=>{});const t=await this.platform.getClient();return(await t.dispatch("get-layout-views",{target:this.identity})).map(t=>this.fin.View.wrapSync(t))}async getRootItem(){this.wire.sendAction("layout-get-root-item").catch(()=>{});const t=await ke(this,Me,"f").getValue(),e=await t.getRoot("layoutName"in this.identity?this.identity:void 0);return be.getEntity(e,t)}async getStackByViewIdentity(t){this.wire.sendAction("layout-get-stack-by-view").catch(()=>{});const e=await ke(this,Me,"f").getValue(),n=await e.getStackByView(t);if(!n)throw new Error(`No stack found for view: ${t.uuid}/${t.name}`);return be.getEntity(n,e)}async addView(t,{location:e,targetView:n}={}){this.wire.sendAction("layout-add-view").catch(t=>{});const{identity:i}=await ke(this,Pe,"m",Se).call(this,"layout-add-view",{viewOptions:t,location:e,targetView:n});return{identity:i}}async closeView(t){this.wire.sendAction("layout-close-view").catch(t=>{}),await ke(this,Pe,"m",Se).call(this,"layout-close-view",{viewIdentity:t})}}Me=new WeakMap,Pe=new WeakSet,Se=async function(t,e){return(await this.platform.getClient()).dispatch(t,{target:this.identity,opts:e})};var Le,$e,Fe,Ge,Re,Oe=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)},We=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n};class je extends l{constructor(){super(...arguments),Le.add(this),$e.set(this,!1),Fe.set(this,null),this.init=async(t={})=>{if(this.wire.recordAnalytic("layout-init"),!this.wire.environment.layoutAllowedInContext(this.fin))throw new Error("Layout.init can only be called from a Window context.");if(Oe(this,$e,"f"))throw new Error("Layout.init was already called, please use Layout.create to add additional layouts.");"openfin"===this.wire.environment.type&&await this.fin.Platform.getCurrentSync().getClient(),We(this,$e,!0,"f"),We(this,Fe,await this.wire.environment.initLayoutManager(this.fin,this.wire,t),"f"),await this.wire.environment.applyLayoutSnapshot(this.fin,Oe(this,Fe,"f"),t);const e={name:this.fin.me.name,uuid:this.fin.me.uuid};if(!t.layoutManagerOverride){const t={layoutName:"__default__",...e};return Oe(this,Ge,"f").call(this,t)}return this.wrapSync(e)},Ge.set(this,t=>{const e="[Layout] You are using a deprecated property `layoutManager` - it will throw if you access it starting in v37.",n=new Proxy({},{get(t,n){throw console.warn(`[Layout-mgr-proxy] accessing ${n.toString()}`),new Error(e)}}),i=Object.assign(this.wrapSync(t),{layoutManager:n});return new Proxy(i,{get(t,n){if("layoutManager"===n)throw console.warn(`[Layout-proxy] accessing ${n.toString()}`),new Error(e);return t[n]}})}),this.getCurrentLayoutManagerSync=()=>Oe(this,Le,"m",Re).call(this,"fin.Platform.Layout.getCurrentLayoutManagerSync()"),this.create=async t=>this.wire.environment.createLayout(Oe(this,Le,"m",Re).call(this,"fin.Platform.Layout.create()"),t),this.destroy=async t=>this.wire.environment.destroyLayout(Oe(this,Le,"m",Re).call(this,"fin.Platform.Layout.destroy()"),t)}async wrap(t){return this.wire.recordAnalytic("layout-wrap"),new Te(t,this.wire)}wrapSync(t){return this.wire.recordAnalytic("layout-wrap-sync"),new Te(t,this.wire)}async getCurrent(){if(this.wire.recordAnalytic("layout-get-current"),"openfin"===this.wire.environment.type&&!this.fin.me.isWindow)throw new Error("You are not in a Window context. Only Windows can have a Layout.");const{uuid:t,name:e}=this.fin.me;return this.wrap({uuid:t,name:e})}getCurrentSync(){if(this.wire.recordAnalytic("layout-get-current-sync"),"openfin"===this.wire.environment.type&&!this.fin.me.isWindow)throw new Error("You are not in a Window context. Only Windows can have a Layout.");const{uuid:t,name:e}=this.fin.me;return this.wrapSync({uuid:t,name:e})}async getLayoutByViewIdentity(t){this.wire.recordAnalytic("layout-get-by-view-identity");let e=await this.wire.environment.getViewWindowIdentity(this.fin,t);e.identity&&(e=e.identity);try{const n=this.wrapSync(e),i=await Te.getClient(n),r=await i.getLayoutIdentityForViewOrThrow(t);return this.wrapSync(r)}catch(n){if(!["No action registered at target for","getLayoutIdentityForViewOrThrow is not a function"].some(t=>n.message.includes(t)))throw n;if(e.uuid===e.name)throw new Error(`View identity ${JSON.stringify(t)} is not attached to any layout in provider window ${JSON.stringify(e)}.`);return this.wrapSync(e)}}}$e=new WeakMap,Fe=new WeakMap,Ge=new WeakMap,Le=new WeakSet,Re=function(t){if(!Oe(this,Fe,"f"))throw new Error(`You must call init before using the API ${t}`);return Oe(this,Fe,"f")};class Ne extends l{constructor(t,e){super(t),this._channel=e,this.Layout=new je(this.wire)}async init(t){if(!fin.__internal_.isPlatform||fin.me.name!==fin.me.uuid)throw new Error("fin.Platform.init should only be called from a custom platform provider running in the main window of the application.");return this.wire.environment.initPlatform(this.fin,t)}async wrap(t){return this.wire.recordAnalytic("platform-wrap"),new he(this.wire,{uuid:t.uuid})}wrapSync(t){return this.wire.recordAnalytic("platform-wrap-sync"),new he(this.wire,{uuid:t.uuid})}async getCurrent(){return this.wire.recordAnalytic("platform-get-current"),this.wrap({uuid:this.wire.me.uuid})}getCurrentSync(){return this.wire.recordAnalytic("platform-get-current-sync"),this.wrapSync({uuid:this.wire.me.uuid})}start(t){return this.wire.recordAnalytic("platform-start"),new Promise(async(e,n)=>{try{const{uuid:n}=t,i=await this.fin.Application._create({...t,isPlatformController:!0});i.once("platform-api-ready",()=>e(this.wrapSync({uuid:n}))),i._run({uuid:n})}catch(t){n(t)}})}startFromManifest(t,e){return this.wire.recordAnalytic("platform-start-from-manifest"),new Promise(async(n,i)=>{try{const i=await this.fin.Application._createFromManifest(t);i.once("platform-api-ready",()=>n(this.wrapSync({uuid:i.identity.uuid}))),i._run(e)}catch(t){i(t)}})}}const He="You are not running in OpenFin.";function Be(t,e,n){return{...{isView:"view"===t,isWindow:"window"===t,isFrame:"iframe"===t,isExternal:"external connection"===t},uuid:e,name:n,entityType:t}}const De=()=>`${Math.random()}${Date.now()}`,Ve=(t,e)=>(...n)=>{try{return t(...n)}catch(t){throw new Error((e||"")+t)}},Ue=(t,e)=>async n=>{try{await t(n)}catch(t){throw console.error(`Error thrown by handler ${e} for context type ${n.type}: ${t}`),t}},ze=(t,e)=>`You have tried to to use ${t} but ${e} has not been overridden in the Interop Broker. Please override this function. Refer to our documentation for more info.`,_e=(t,e,n,i)=>{const{uuid:r,name:s}=n;return i?`Entity with identity: ${r}/${s} has called ${i} or ${t} but ${e} has not been overridden.`:`Entity with identity: ${r}/${s} has called ${t} but ${e} has not been overridden.`},qe={fireIntent:ze("fireIntent","handleFiredIntent"),fireIntentForContext:ze("fireIntentForContext","handleFiredIntentForContext"),getInfoForIntent:ze("getInfoForIntent","handleInfoForIntent"),getInfoForIntentsByContext:ze("getInfoForIntentsByContext","handleInfoForIntentsByContext"),joinSessionContextGroupWithJoinContextGroup:"The Context Group you have tried to join is a Session Context Group. Custom Context Groups can only be defined by the Interop Broker through code or manifest configuration. Please use joinSessionContextGroup.",fdc3Open:ze("fdc3.open","fdc3HandleOpen"),fdc3FindInstances:ze("fdc3.findInstances","fdc3HandleFindInstances"),fdc3GetAppMetadata:ze("fdc3.getAppMetadata","fdc3HandleGetAppMetadata"),fdc3GetInfo:ze("fdc3.getInfo","fdc3HandleGetInfo")},Je=t=>t?"object"!=typeof t?{isValid:!1,reason:"Context must be an Object"}:t.type?{isValid:!0}:{isValid:!1,reason:"Context must have a type property"}:{isValid:!1,reason:"No context supplied"};class Ye{constructor(t,e){this.provider=t,this.id=e,this.lastContext=void 0,this.contextGroupMap=new Map,this.clients=new Map,this.registerListeners()}registerListeners(){this.provider.register(`sessionContextGroup:getContext-${this.id}`,this.getCurrentContext.bind(this)),this.provider.register(`sessionContextGroup:setContext-${this.id}`,this.setContext.bind(this)),this.provider.register(`sessionContextGroup:handlerAdded-${this.id}`,this.handlerAdded.bind(this)),this.provider.register(`sessionContextGroup:handlerRemoved-${this.id}`,this.handlerRemoved.bind(this))}getCurrentContext(t){return t.type?this.contextGroupMap.get(t.type):this.lastContext}setContext(t,e){const{context:n}=t,i=Je(n);if(!1===i.isValid)throw new Error(`Failed to set Context - bad Context. Reason: ${i.reason}. Context: ${JSON.stringify(n)}`);if(!this.getClientState(e))throw new Error(`Client with Identity: ${e.uuid} ${e.name} not in Session Client State Map`);this.contextGroupMap.set(n.type,n),this.lastContext=n;Array.from(this.clients.values()).forEach(t=>{t.contextHandlers.get(n.type)?.forEach(e=>{this.provider.dispatch(t.clientIdentity,e,n)}),t.globalHandler&&this.provider.dispatch(t.clientIdentity,t.globalHandler,n)})}getClientState(t){return this.clients.get(t.endpointId)}async handlerAdded(t,e){const{handlerId:n,contextType:i}=t,r=this.getClientState(e);if(!r)throw new Error(`Client with Identity: ${e.uuid} ${e.name} not in Client State Map`);if(i){const t=r.contextHandlers.get(i)||[];r.contextHandlers.set(i,[...t,n]);const s=this.contextGroupMap.get(i);s&&await this.provider.dispatch(e,n,s)}else{r.globalHandler=n;const t=[...this.contextGroupMap.keys()].map(async t=>{const i=this.contextGroupMap.get(t);i&&await this.provider.dispatch(e,n,i)});await Promise.all(t)}}handlerRemoved(t,e){const{handlerId:n}=t,i=this.clients.get(e.endpointId);i?(Array.from(i.contextHandlers).forEach(([,t])=>{const e=t.indexOf(n);e>-1&&t.splice(e,1)}),i.globalHandler===n&&(i.globalHandler=void 0)):console.warn(`Trying to remove a handler from a client that isn't mapped. handlerId: ${n}. clientIdentity: ${e}`)}registerNewClient(t){if(!this.clients.has(t.endpointId)){const e={contextHandlers:new Map,clientIdentity:t,globalHandler:void 0};this.clients.set(t.endpointId,e)}}onDisconnection(t){this.clients.delete(t.endpointId)}}class Ke{constructor(t,e,n){this.provider=t,this.id=e,this.clients=new Map,this.registerListeners(),this.contextByContextType=new Map,this.lastContext=void 0,this.provider.onConnection(t=>this.registerNewClient(t)),this.removePrivateChannelProvider=n,this.provider.onDisconnection(async t=>{const{endpointId:e}=t;this.clients.has(e)&&await this.handleClientDisconnecting(t),0===(await this.provider.getAllClientInfo()).length&&(this.provider.destroy(),this.removePrivateChannelProvider(this.id))})}getClientState(t){return this.clients.get(t.endpointId)}registerListeners(){this.provider.register("broadcast",this.broadcast.bind(this)),this.provider.register("getCurrentContext",this.getCurrentContext.bind(this)),this.provider.register("contextHandlerAdded",this.contextHandlerAdded.bind(this)),this.provider.register("contextHandlerRemoved",this.contextHandlerRemoved.bind(this)),this.provider.register("nonStandardHandlerRemoved",this.nonStandardHandlerRemoved.bind(this)),this.provider.register("onAddContextHandlerAdded",this.onAddContextHandlerAdded.bind(this)),this.provider.register("onDisconnectHandlerAdded",this.onDisconnectHandlerAdded.bind(this)),this.provider.register("onUnsubscribeHandlerAdded",this.onUnsubscribeHandlerAdded.bind(this)),this.provider.register("clientDisconnecting",(t,e)=>{this.handleClientDisconnecting(e)})}broadcast(t,e){const{context:n}=t;if(!this.getClientState(e))throw new Error(`Client with Identity: ${e.uuid} ${e.name}, tried to call broadcast, is not connected to this Private Channel`);const i=Je(n);if(!1===i.isValid)throw new Error(`Failed to broadcast - bad Context. Reason: ${i.reason}. Context: ${JSON.stringify(n)}`);this.contextByContextType.set(n.type,n),this.lastContext=n,Array.from(this.clients.values()).forEach(t=>{const e=t.handlerIdsByContextTypes.get(n.type);e&&e.forEach(e=>{this.provider.dispatch(t.clientIdentity,e,n)}),t.globalHandler&&this.provider.dispatch(t.clientIdentity,t.globalHandler,n)})}getCurrentContext(t,e){const{contextType:n}=t;if(!this.getClientState(e))throw new Error(`Client with Identity: ${e.uuid} ${e.name}, tried to call getCurrentContext, is not connected to this Private Channel`);if(void 0!==n){const t=this.contextByContextType.get(n);return t||null}return this.lastContext?this.lastContext:null}contextHandlerAdded(t,e){const{handlerId:n,contextType:i}=t,r=this.getClientState(e);if(!r)throw new Error(`Client with Identity: ${e.uuid} ${e.name}, tried to call addContextListener, is not connected to this Private Channel`);if(i){const t=r.handlerIdsByContextTypes.get(i)||[];r.handlerIdsByContextTypes.set(i,[...t,n])}else r.globalHandler=n;Array.from(this.clients.values()).forEach(t=>{t.clientIdentity.endpointId!==e.endpointId&&t.onAddContextListenerHandlerId&&this.provider.dispatch(t.clientIdentity,t.onAddContextListenerHandlerId,i)})}async contextHandlerRemoved(t,e){const{handlerId:n}=t,i=this.getClientState(e);if(i){let t;if(i.globalHandler===n)i.globalHandler=void 0;else for(const[e,r]of i.handlerIdsByContextTypes){const i=r.indexOf(n);i>-1&&(r.splice(i,1),t=e)}const r=(await this.getConnectedClients()).map(async n=>{const{clientIdentity:i,clientIdentity:{endpointId:r},onUnsubscribeHandlerId:s}=n;r!==e.endpointId&&s&&await this.provider.dispatch(i,s,t)});try{await Promise.all(r)}catch(t){throw console.error(`Problem when attempting to dispatch to onUnsubscribeHandlers. Error: ${t} Removing Client: ${n}. uuid: ${e.uuid}. name: ${e.name}. endpointId: ${e.endpointId}`),new Error(t)}}else console.warn(`Trying to remove a handler from a client that isn't mapped. handlerId: ${n}. uuid: ${e.uuid}. name: ${e.name}. endpointId: ${e.endpointId}.`)}nonStandardHandlerRemoved(t,e){const{handlerId:n}=t,i=this.getClientState(e);i?i.onDisconnectHandlerId===n?i.onDisconnectHandlerId=void 0:i.onAddContextListenerHandlerId===n?i.onAddContextListenerHandlerId=void 0:i.onUnsubscribeHandlerId===n&&(i.onUnsubscribeHandlerId=void 0):console.warn(`Trying to remove a handler from a client that isn't mapped. handlerId: ${n}. clientIdentity: ${e}`)}onAddContextHandlerAdded(t,e){const n=this.getClientState(e),{handlerId:i}=t;if(!n)throw new Error(`Client with Identity: ${e.uuid} ${e.name}, tried to call onAddContextListener, is not connected to this Private Channel`);n.onAddContextListenerHandlerId=i,Array.from(this.clients.values()).forEach(t=>{t.clientIdentity.endpointId!==e.endpointId&&Array.from(t.handlerIdsByContextTypes.keys()).forEach(t=>{this.provider.dispatch(e,i,t)})})}onDisconnectHandlerAdded(t,e){const n=this.getClientState(e),{handlerId:i}=t;if(!n)throw new Error(`Client with Identity: ${e.uuid} ${e.name}, tried to call onDisconnect, is not connected to this Private Channel`);n.onDisconnectHandlerId=i}onUnsubscribeHandlerAdded(t,e){const n=this.getClientState(e),{handlerId:i}=t;if(!n)throw new Error(`Client with Identity: ${e.uuid} ${e.name}, tried to call onUnsubscribe, is not connected to this Private Channel`);n.onUnsubscribeHandlerId=i}removeClient(t){const e=this.getClientState(t);if(!e)throw new Error(`Client with Identity: ${t.uuid} ${t.name}, tried to call disconnect, is not connected to this Private Channel`);e.handlerIdsByContextTypes.clear(),this.clients.delete(t.endpointId)}async fireOnDisconnectForOtherClients(t){const{endpointId:e}=t,n=(await this.getConnectedClients()).map(async t=>{const{clientIdentity:{endpointId:n},onDisconnectHandlerId:i}=t;n!==e&&i&&await this.provider.dispatch(t.clientIdentity,i)});try{await Promise.all(n)}catch(e){throw console.error(`Problem when attempting to dispatch to onDisconnectHandlers. Error: ${e} Disconnecting Client: uuid: ${t.uuid}. name: ${t.name}. endpointId: ${t.endpointId}`),new Error(e)}}async unsubscribeAll(t){const{endpointId:e}=t,n=this.clients.get(e);if(n){const e=Array.from(n.handlerIdsByContextTypes.values()).flat(),i=n.globalHandler;if(e.length>0){const n=e.map(async e=>this.contextHandlerRemoved({handlerId:e},t));try{await Promise.all(n)}catch(t){console.error(t.message)}}if(i)try{await this.contextHandlerRemoved({handlerId:i},t)}catch(t){console.error(t.message)}}}async handleClientDisconnecting(t){await this.unsubscribeAll(t),this.removeClient(t),await this.fireOnDisconnectForOtherClients(t)}registerNewClient(t){if(!this.clients.has(t.endpointId)){const e={clientIdentity:t,handlerIdsByContextTypes:new Map,globalHandler:void 0,onAddContextListenerHandlerId:void 0,onUnsubscribeHandlerId:void 0,onDisconnectHandlerId:void 0};this.clients.set(t.endpointId,e)}}async getConnectedClients(){const t=await this.provider.getAllClientInfo();return Array.from(this.clients.values()).filter(e=>{const{uuid:n,name:i}=e.clientIdentity;return t.some(t=>i===t.name&&n===t.uuid)})}static init(t,e,n){return new Ke(t,e,n)}}const Ze={"fdc3.channel.1":{name:"Channel 1",color:"red",glyph:"1"},"fdc3.channel.2":{name:"Channel 2",color:"orange",glyph:"2"},"fdc3.channel.3":{name:"Channel 3",color:"yellow",glyph:"3"},"fdc3.channel.4":{name:"Channel 4",color:"green",glyph:"4"},"fdc3.channel.5":{name:"Channel 5",color:"cyan",glyph:"5"},"fdc3.channel.6":{name:"Channel 6",color:"blue",glyph:"6"},"fdc3.channel.7":{name:"Channel 7",color:"magenta",glyph:"7"},"fdc3.channel.8":{name:"Channel 8",color:"purple",glyph:"8"}},Qe={red:"fdc3.channel.1",orange:"fdc3.channel.2",yellow:"fdc3.channel.3",green:"fdc3.channel.4",teal:"fdc3.channel.5",blue:"fdc3.channel.6",pink:"fdc3.channel.7",indigo:"fdc3.channel.8",purple:"fdc3.channel.8"};var Xe,tn,en,nn=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},rn=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};const sn=Object.entries(Ze).map(([t,e])=>({id:t,displayMetadata:e}));class on extends l{constructor(t,e,n){super(t),Xe.set(this,void 0),tn.set(this,void 0),en.set(this,void 0),this.getProvider=()=>rn(this,en,"f").getValue(),this.interopClients=new Map,this.contextGroupsById=new Map,nn(this,tn,n.contextGroups??[...sn],"f"),nn(this,Xe,n.fdc3Info,"f"),n?.logging&&(this.logging=n.logging),this.intentClientMap=new Map,this.lastContextMap=new Map,this.sessionContextGroupMap=new Map,this.privateChannelProviderMap=new Map,nn(this,en,new A(e),"f"),this.setContextGroupMap(),this.setupChannelProvider()}static createClosedConstructor(...t){return class extends on{constructor(...n){if(n.length){const[i,r,s]=n;if(s&&"object"==typeof s&&!e(s,t[2]))return console.warn("You have modified the parameters of the InteropOverride constructor. This behavior is deprecated and will be removed in a future version. You can modify these options in your manifest. Please consult our Interop docs for guidance on migrating to the new override scheme."),void super(t[0],t[1],s);console.warn("You are attempting to pass arguments to the InteropOverride constructor. This is not necessary, and these passed arguments will be ignored. You are likely using an older InteropBroker override scheme. Please consult our Interop docs for guidance on migrating to the new override scheme.")}super(...t)}}}setContext({context:t},e){this.wire.sendAction("interop-broker-set-context").catch(t=>{});const n=this.getClientState(e);if(!n||!n.contextGroupId)throw n?new Error("You must join a context group before you can set context."):new Error(`Client with Identity: ${e.uuid} ${e.name} not in Client State Map`);{const{contextGroupId:e}=n;this.setContextForGroup({context:t},e)}}setContextForGroup({context:t},e){this.wire.sendAction("interop-broker-set-context-for-group").catch(t=>{});const n=this.normalizeContextGroupId(e);if(void 0===n)return;const i=this.contextGroupsById.get(n);if(!i)throw new Error(`Unable to set context for context group that isn't in the context group mapping: ${n}.`);const r=on.checkContextIntegrity(t);if(!1===r.isValid)throw new Error(`Failed to set Context - bad Context. Reason: ${r.reason}. Context: ${JSON.stringify(t)}`);const s=t.type;i.set(s,t),this.lastContextMap.set(n,s);Array.from(this.interopClients.values()).filter(t=>t.contextGroupId===n).forEach(e=>{for(const[,n]of e.contextHandlers)on.isContextTypeCompatible(s,n.contextType)&&this.invokeContextHandler(e.clientIdentity,n.handlerId,t)})}getCurrentContext(t,e){this.wire.sendAction("interop-broker-get-current-context").catch(t=>{});const n=this.getClientState(e);if(!n?.contextGroupId)throw new Error("You must be a member of a context group to call getCurrentContext");const{contextGroupId:i}=n,r=this.contextGroupsById.get(i),s=this.lastContextMap.get(i),o=t?.contextType??s;return r&&o?r.get(o):void 0}async joinContextGroup({contextGroupId:t,target:e},n){this.wire.sendAction("interop-broker-join-context-group").catch(t=>{});const i=this.normalizeContextGroupId(t);if(void 0!==i){if(this.sessionContextGroupMap.has(i))throw new Error(qe.joinSessionContextGroupWithJoinContextGroup);if(e){on.hasEndpointId(e)&&await this.addClientToContextGroup({contextGroupId:i},e);try{const t=this.channel.connections.filter(t=>t.uuid===e.uuid&&t.name===e.name);if(!t.length)throw new Error(`Given Identity ${e.uuid} ${e.name} is not connected to the Interop Broker.`);t.length>1&&console.warn(`More than one connection found for identity ${e.uuid} ${e.name}`);const n=[];for(const e of t)n.push(this.addClientToContextGroup({contextGroupId:i},e));await Promise.all(n)}catch(t){throw new Error(t)}}else await this.addClientToContextGroup({contextGroupId:i},n)}else e?await this.removeFromContextGroup({target:e},n):await this.removeClientFromContextGroup(n)}async addClientToContextGroup({contextGroupId:t},e){this.wire.sendAction("interop-broker-add-client-to-context-group").catch(t=>{});const n=this.normalizeContextGroupId(t);if(void 0===n)return void await this.removeClientFromContextGroup(e);const i=this.getClientState(e);if(!i)throw new Error(`Client with Identity: ${e.uuid} ${e.name} not in Client State Map`);if(!this.getContextGroups().find(t=>t.id===n))throw new Error(`Attempting to join a context group that does not exist: ${n}. You may only join existing context groups.`);const r=i.contextGroupId;if(r!==n){i.contextGroupId=n,await this.setCurrentContextGroupInClientOptions(e,n);const t=this.contextGroupsById.get(n);for(const[,n]of i.contextHandlers){const{contextType:i,handlerId:r}=n;if(void 0===i)t.forEach((t,n)=>{this.invokeContextHandler(e,r,t)});else if(t.has(i)){const n=t.get(i);n&&this.invokeContextHandler(e,r,n)}}Promise.allSettled(this.channel.publish("client-changed-context-group",{identity:e,contextGroupId:n,previousContextGroupId:r||null}))}}async removeFromContextGroup({target:t},e){if(this.wire.sendAction("interop-broker-remove-from-context-group").catch(t=>{}),t){on.hasEndpointId(t)&&await this.removeClientFromContextGroup(t);try{const e=this.channel.connections.filter(e=>e.uuid===t.uuid&&e.name===t.name);if(!e.length)throw new Error(`No connection found for given Identity ${t.uuid} ${t.name}`);e.length>1&&console.warn(`More than one connection found for identity ${t.uuid} ${t.name}`);const n=[];for(const t of e)n.push(this.removeClientFromContextGroup(t));await Promise.all(n)}catch(t){throw new Error(t)}}else await this.removeClientFromContextGroup(e)}async removeClientFromContextGroup(t){this.wire.sendAction("interop-broker-remove-client-from-context-group").catch(t=>{});const e=this.getClientState(t),n=e?.contextGroupId;e&&(e.contextGroupId=void 0),await this.setCurrentContextGroupInClientOptions(t,null),void 0!==n&&Promise.allSettled(this.channel.publish("client-changed-context-group",{identity:t,contextGroupId:null,previousContextGroupId:n||null}))}getContextGroups(){return this.wire.sendAction("interop-broker-get-context-groups").catch(t=>{}),rn(this,tn,"f").map(t=>({...t}))}getInfoForContextGroup({contextGroupId:t}){this.wire.sendAction("interop-broker-get-info-for-context-group").catch(t=>{});const e=this.normalizeContextGroupId(t);if(void 0!==e)return this.getContextGroups().find(t=>t.id===e)}getAllClientsInContextGroup({contextGroupId:t}){this.wire.sendAction("interop-broker-get-all-clients-in-context-group").catch(t=>{});const e=this.normalizeContextGroupId(t);if(void 0===e)return[];return Array.from(this.interopClients.values()).filter(t=>t.contextGroupId===e).map(t=>t.clientIdentity)}async handleFiredIntent(t,e){const n=_e("fdc3.raiseIntent","InteropBroker.handleFiredIntent",e,"interopClient.fireIntent");throw console.warn(n),new Error(qe.fireIntent)}async setIntentTarget(t,e){this.wire.sendAction("interop-broker-set-intent-target").catch(t=>{});const n=this.intentClientMap.get(e.name),i=`intent-handler-${t.name}`;if(n){const e=n.get(i);if(e){if(e.pendingIntents.push(t),e.clientIdentity&&e.isReady){const{clientIdentity:t,pendingIntents:n}=e;try{const r=n[n.length-1];await this.invokeIntentHandler(t,i,r),e.pendingIntents=[]}catch(n){console.error(`Error invoking intent handler for client ${t.uuid}/${t.name}/${t.endpointId}`),e.isReady=!1}}}else n.set(i,{isReady:!1,pendingIntents:[t]})}else{this.intentClientMap.set(e.name,new Map);const n=this.intentClientMap.get(e.name);n&&n.set(i,{isReady:!1,pendingIntents:[t]})}}async handleInfoForIntent(t,e){const n=_e("fdc3.findIntent","InteropBroker.handleInfoForIntent",e,"interopClient.getInfoForIntent");throw console.warn(n),new Error(qe.getInfoForIntent)}async handleInfoForIntentsByContext(t,e){const n=_e("fdc3.findIntentsByContext","InteropBroker.handleInfoForIntentsByContext",e,"interopClient.getInfoForIntentsByContext");throw console.warn(n),new Error(qe.getInfoForIntentsByContext)}async handleFiredIntentForContext(t,e){const n=_e("fdc3.raiseIntentForContext","InteropBroker.handleFiredIntentForContext",e,"interopClient.fireIntentForContext");throw console.warn(n),new Error(qe.fireIntentForContext)}async clientDisconnected(t){}async fdc3HandleOpen({app:t,context:e},n){const i=_e("fdc3.open","InteropBroker.fdc3HandleOpen",n);throw console.warn(i),new Error(qe.fdc3Open)}async fdc3HandleFindInstances(t,e){const n=_e("fdc3.open","InteropBroker.fdc3HandleFindInstances",e);throw console.warn(n),new Error(qe.fdc3FindInstances)}async fdc3HandleGetAppMetadata(t,e){const n=_e("fdc3.getAppMetadata","InteropBroker.fdc3HandleGetAppMetadata",e);throw console.warn(n),new Error(qe.fdc3GetAppMetadata)}async invokeContextHandler(t,e,n){const i=await this.getProvider();try{await i.dispatch(t,e,n)}catch(i){console.error(`Error invoking context handler ${e} for context type ${n.type} in client ${t.uuid}/${t.name}/${t.endpointId}`,i)}}async invokeIntentHandler(t,e,n){const i=await this.getProvider();await i.dispatch(t,e,n)}async fdc3HandleGetInfo(t,e){const{fdc3Version:n}=t;return{fdc3Version:n,...rn(this,Xe,"f"),optionalFeatures:{OriginatingAppMetadata:!1,UserChannelMembershipAPIs:!0},appMetadata:{appId:"",instanceId:""}}}async getAllClientInfo(){return(await this.getProvider()).getAllClientInfo()}decorateSnapshot(t){return{...t,interopSnapshotDetails:{contextGroupStates:this.getContextGroupStates()}}}applySnapshot(t,e){const n=t?.interopSnapshotDetails?.contextGroupStates;if(n){const t=this.normalizeContextGroupStates(n);e?.closeExistingWindows||this.updateExistingClients(t),this.rehydrateContextGroupStates(t)}}updateExistingClients(t){this.interopClients.forEach(e=>{const{clientIdentity:n,contextGroupId:i,contextHandlers:r}=e;if(i){const e=t[i];for(const[,t]of Object.entries(e))r.forEach(e=>{const{handlerId:i,contextType:r}=e;on.isContextTypeCompatible(t.type,r)&&this.invokeContextHandler(n,i,t)})}})}getContextGroupStates(){return on.toObject(this.contextGroupsById)}rehydrateContextGroupStates(t){const e=Object.entries(t);for(const[t,n]of e){const e=Object.entries(n);for(const[n,i]of e)if(this.contextGroupsById.has(t)){this.contextGroupsById.get(t).set(n,i)}else console.warn(`Attempting to set a context group that isn't in the context group mapping. Skipping context group rehydration for: ${t}`)}}contextHandlerRegistered({contextType:t,handlerId:e},n){const i={contextType:t,handlerId:e},r=this.getClientState(n);if(r?.contextHandlers.set(e,i),r&&r.contextGroupId){const{contextGroupId:i}=r,s=this.contextGroupsById.get(i);if(void 0===t)s.forEach((t,i)=>{this.invokeContextHandler(n,e,t)});else if(s.has(t)){const i=s.get(t);i&&this.invokeContextHandler(n,e,i)}}}async intentHandlerRegistered(t,e){const{handlerId:n}=t,i=this.intentClientMap.get(e.name),r=i?.get(n);if(i)if(r){const{pendingIntents:t}=r;r.clientIdentity=e,r.isReady=!0;try{if(t.length>0){const i=t[t.length-1];await this.invokeIntentHandler(e,n,i),r.pendingIntents=[]}}catch(t){console.error(`Error invoking intent handler: ${n} for client ${e.uuid}/${e.name}/${e.endpointId}`)}}else i.set(n,{isReady:!0,pendingIntents:[],clientIdentity:e});else{this.intentClientMap.set(e.name,new Map);const t=this.intentClientMap.get(e.name);t&&t.set(n,{isReady:!0,pendingIntents:[],clientIdentity:e})}}removeContextHandler({handlerId:t},e){const n=this.getClientState(e);n&&n.contextHandlers.delete(t)}handleJoinSessionContextGroup({sessionContextGroupId:t},e){try{if(!t)throw new Error("Failed to join session context group: must specify group id.");const n=this.sessionContextGroupMap.get(t);if(n)n.registerNewClient(e);else{const n=new Ye(this.channel,t);n.registerNewClient(e),this.sessionContextGroupMap.set(t,n)}return{hasConflict:this.contextGroupsById.has(t)}}catch(t){throw new Error(t)}}getClientState(t){return this.interopClients.get(t.endpointId)}static toObject(t){const e=Object.fromEntries(t),n={};return Object.entries(e).forEach(([t,e])=>{const i=Object.fromEntries(e);n[t]=i}),n}normalizeContextGroupStates(t){const e={};for(const[n,i]of Object.entries(t)){const t=this.normalizeContextGroupId(n);void 0!==t&&(e[t]={...e[t],...i})}return e}normalizeContextGroupId(t){return Object.keys(Ze).every(t=>this.contextGroupsById.has(t))?function(t){if("gray"!==t)return Object.prototype.hasOwnProperty.call(Qe,t)?Qe[t]:t}(t):t}static hasEndpointId(t){return void 0!==t.endpointId}static isContextTypeCompatible(t,e){return void 0===e||t===e}setContextGroupMap(){for(const t of this.getContextGroups())this.contextGroupsById.set(t.id,new Map)}async setCurrentContextGroupInClientOptions(t,e){try{const n=await this.fin.System.getEntityInfo(t.uuid,t.name);let i;"view"===n.entityType?i=await this.fin.View.wrap(t):"window"===n.entityType&&(i=await this.fin.Window.wrap(t)),i&&await i.updateOptions({interop:{currentContextGroup:e}})}catch(t){}}async setupChannelProvider(){try{const t=await this.getProvider();this.channel=t,this.wireChannel(t)}catch(t){throw new Error(`Error setting up Interop Broker Channel Provider: ${t}`)}}wireChannel(t){t.onConnection(async(t,e)=>{if(!await this.isConnectionAuthorized(t,e))throw new Error(`Connection not authorized for ${t.uuid}, ${t.name}`);if(!t.endpointId)throw new Error("Version too old to be compatible with Interop. Please upgrade your runtime to a more recent version.");const n={contextGroupId:void 0,contextHandlers:new Map,clientIdentity:t},i=e?.currentContextGroup?this.normalizeContextGroupId(e.currentContextGroup):void 0;i&&this.contextGroupsById.has(i)&&(n.contextGroupId=i,i!==e.currentContextGroup&&await this.setCurrentContextGroupInClientOptions(t,i)),this.interopClients.set(t.endpointId,n)}),t.onDisconnection(t=>{this.interopClients.delete(t.endpointId);const e=this.intentClientMap.get(t.name);e&&t.uuid===this.fin.me.uuid&&e.forEach(t=>{t.isReady=!1}),this.sessionContextGroupMap.forEach(e=>{e.onDisconnection(t)}),this.clientDisconnected(t)}),t.beforeAction(async(t,e,n)=>{if(!await this.isActionAuthorized(t,e,n))throw new Error(`Action (${t}) not authorized for ${n.uuid}, ${n.name}`);this.logging?.beforeAction?.enabled&&console.log(t,e,n)}),t.afterAction((t,e,n)=>{if(this.logging?.afterAction?.enabled){const i=e?[t,e,n]:[t,n];console.log(...i)}}),t.register("setContext",this.setContext.bind(this)),t.register("fireIntent",this.handleFiredIntent.bind(this)),t.register("getCurrentContext",this.getCurrentContext.bind(this)),t.register("getInfoForIntent",this.handleInfoForIntent.bind(this)),t.register("getInfoForIntentsByContext",this.handleInfoForIntentsByContext.bind(this)),t.register("fireIntentForContext",this.handleFiredIntentForContext.bind(this)),t.register("getContextGroups",this.getContextGroups.bind(this)),t.register("joinContextGroup",this.joinContextGroup.bind(this)),t.register("removeFromContextGroup",this.removeFromContextGroup.bind(this)),t.register("getAllClientsInContextGroup",this.getAllClientsInContextGroup.bind(this)),t.register("getInfoForContextGroup",this.getInfoForContextGroup.bind(this)),t.register("contextHandlerRegistered",this.contextHandlerRegistered.bind(this)),t.register("intentHandlerRegistered",this.intentHandlerRegistered.bind(this)),t.register("removeContextHandler",this.removeContextHandler.bind(this)),t.register("sessionContextGroup:createIfNeeded",this.handleJoinSessionContextGroup.bind(this)),t.register("fdc3Open",this.fdc3HandleOpen.bind(this)),t.register("fdc3v2FindIntentsByContext",this.handleInfoForIntentsByContext.bind(this)),t.register("fdc3FindInstances",this.fdc3HandleFindInstances.bind(this)),t.register("fdc3GetAppMetadata",this.fdc3HandleGetAppMetadata.bind(this)),t.register("fdc3v2GetInfo",async(t,e)=>this.fdc3HandleGetInfo.bind(this)(t,e)),t.register("createPrivateChannelProvider",async t=>{const{channelId:e}=t,n=await this.fin.InterApplicationBus.Channel.create(e),i=Ke.init(n,e,t=>{this.privateChannelProviderMap.delete(t)});this.privateChannelProviderMap.set(e,i)}),t.register("isIdUsedByPrivateChannel",async t=>{const{channelId:e}=t;return this.privateChannelProviderMap.has(e)})}isConnectionAuthorized(t,e){return this.wire.sendAction("interop-broker-is-connection-authorized").catch(t=>{}),Promise.resolve(!0)}isActionAuthorized(t,e,n){return this.wire.sendAction("interop-broker-is-action-authorized").catch(t=>{}),Promise.resolve(!0)}}Xe=new WeakMap,tn=new WeakMap,en=new WeakMap,on.checkContextIntegrity=Je;var an,cn=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},dn=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};an=new WeakMap;var hn,ln,pn,un,wn,yn,fn,gn,mn=class extends l{constructor(t,e,n){super(t),an.set(this,void 0),this.id=n,cn(this,an,e,"f")}async setContext(t){this.wire.sendAction("interop-session-context-group-set-context").catch(t=>{});return(await dn(this,an,"f")).dispatch(`sessionContextGroup:setContext-${this.id}`,{sessionContextGroupId:this.id,context:t})}async getCurrentContext(t){this.wire.sendAction("interop-session-context-group-get-context").catch(t=>{});return(await dn(this,an,"f")).dispatch(`sessionContextGroup:getContext-${this.id}`,{sessionContextGroupId:this.id,type:t})}async addContextHandler(t,e){if(this.wire.sendAction("interop-session-context-group-add-handler").catch(t=>{}),"function"!=typeof t)throw new Error("Non-function argument passed to the first parameter 'handler'. Be aware that the argument order does not match the FDC3 standard.");const n=await dn(this,an,"f");let i;return i=e?`sessionContextHandler:invoke-${this.id}-${e}-${De()}`:`sessionContextHandler:invoke-${this.id}`,n.register(i,Ue(t,i)),await n.dispatch(`sessionContextGroup:handlerAdded-${this.id}`,{handlerId:i,contextType:e}),{unsubscribe:await this.createUnsubscribeCb(i)}}async createUnsubscribeCb(t){const e=await dn(this,an,"f");return async()=>{e.remove(t),await e.dispatch(`sessionContextGroup:handlerRemoved-${this.id}`,{handlerId:t})}}getUserInstance(){return{id:this.id,setContext:Ve(this.setContext.bind(this),"Failed to set context: "),getCurrentContext:Ve(this.getCurrentContext.bind(this),"Failed to get context: "),addContextHandler:Ve(this.addContextHandler.bind(this),"Failed to add context handler: ")}}},vn=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},Cn=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class In{constructor(t){ln.set(this,void 0),pn.set(this,!1),wn.set(this,async()=>{const t=await Cn(this,ln,"f");let e=Cn(hn,hn,"f",un).get(t);return e||(e={},Cn(hn,hn,"f",un).set(t,e)),e}),yn.set(this,t=>{const e=[];let n;const i=t=>{e.forEach(e=>e(t))};return{callbacks:e,dispose:async n=>{const i=e.indexOf(n);if(i>=0&&(e.splice(i,1),0===e.length)){(await Cn(this,ln,"f")).remove(t)}},waitForRegistration:async()=>{n||(n=(async()=>{const e=await Cn(this,ln,"f");await e.register(t,i)})()),await n}}}),fn.set(this,async t=>(await Cn(this,wn,"f").call(this))[t]),gn.set(this,async t=>{const e=await Cn(this,wn,"f").call(this);return await Cn(this,fn,"f").call(this,t)||(e[t]=Cn(this,yn,"f").call(this,t)),e[t]}),this.addListener=async(t,e)=>{const n=await Cn(this,gn,"f").call(this,t);n.callbacks.push(e),await n.waitForRegistration()},this.removeListener=async(t,e)=>{if(!Cn(this,pn,"f"))return;if(await Cn(this,fn,"f").call(this,t)){const n=await Cn(this,gn,"f").call(this,t);await n.dispose(e)}},vn(this,ln,t,"f"),Promise.resolve(t).then(()=>{vn(this,pn,!0,"f")}).catch(()=>{console.warn("Channel Connection error occurred in channel client. Channel-events registrations will fail.")})}}hn=In,ln=new WeakMap,pn=new WeakMap,wn=new WeakMap,yn=new WeakMap,fn=new WeakMap,gn=new WeakMap,un={value:new WeakMap};var bn,xn,An,En,Pn=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},Mn=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class Sn extends l{constructor(t,e,n){super(t),bn.set(this,void 0),xn.set(this,void 0),An.set(this,void 0),En.set(this,void 0),this.addListener=async(t,e)=>{try{await Mn(this,En,"f").addListener(t,e)}catch(e){throw new Error(`An unexpected error occurred when adding a listener to the event ${t}. \n${e.stack}.`)}},this.removeListener=async(t,e)=>{try{await Mn(this,En,"f").removeListener(t,e)}catch(e){throw new Error(`An unexpected error occurred when removing a listener for the event ${t}. \n${e.stack}.`)}},Pn(this,xn,new Map,"f"),Pn(this,bn,e,"f"),Pn(this,An,n,"f"),Pn(this,En,new In(e),"f")}async setContext(t){this.wire.sendAction("interop-client-set-context").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("setContext",{context:t})}async addContextHandler(t,e){if(this.wire.sendAction("interop-client-add-context-handler").catch(t=>{}),"function"!=typeof t)throw new Error("Non-function argument passed to the first parameter 'handler'. Be aware that the argument order does not match the FDC3 standard.");const n=await Mn(this,bn,"f");let i;i=e?`invokeContextHandler-${e}-${De()}`:"invokeContextHandler";const r=Ue(t,i);return n.register(i,r),await n.dispatch("contextHandlerRegistered",{handlerId:i,contextType:e}),{unsubscribe:async()=>{n.remove(i),await n.dispatch("removeContextHandler",{handlerId:i})}}}async getContextGroups(){this.wire.sendAction("interop-client-get-context-groups").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("getContextGroups")}async joinContextGroup(t,e){this.wire.sendAction("interop-client-join-context-group").catch(t=>{});const n=await Mn(this,bn,"f");if(!t)throw new Error("No contextGroupId specified for joinContextGroup.");return n.dispatch("joinContextGroup",{contextGroupId:t,target:e})}async removeFromContextGroup(t){this.wire.sendAction("interop-client-remove-from-context-group").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("removeFromContextGroup",{target:t})}async getAllClientsInContextGroup(t){this.wire.sendAction("interop-client-get-all-clients-in-context-group").catch(t=>{});const e=await Mn(this,bn,"f");if(!t)throw new Error("No contextGroupId specified for getAllClientsInContextGroup.");return e.dispatch("getAllClientsInContextGroup",{contextGroupId:t})}async getInfoForContextGroup(t){this.wire.sendAction("interop-client-get-info-for-context-group").catch(t=>{});const e=await Mn(this,bn,"f");if(!t)throw new Error("No contextGroupId specified for getInfoForContextGroup.");return e.dispatch("getInfoForContextGroup",{contextGroupId:t})}async fireIntent(t){this.wire.sendAction("interop-client-fire-intent").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("fireIntent",t)}async registerIntentHandler(t,e,n){this.wire.sendAction("interop-client-register-intent-handler").catch(t=>{});const i=await Mn(this,bn,"f"),r=`intent-handler-${e}`,s=((t,e)=>async n=>{try{return t(n)}catch(t){throw console.error(`Error thrown by handler ${e}: ${t}`),t}})(t,r);try{await i.register(r,s),await i.dispatch("intentHandlerRegistered",{handlerId:r,...n})}catch(t){throw new Error("Unable to register intent handler")}return{unsubscribe:async()=>{i.remove(r)}}}async getCurrentContext(t){this.wire.sendAction("interop-client-get-current-context").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("getCurrentContext",{contextType:t})}async getInfoForIntent(t){this.wire.sendAction("interop-client-get-info-for-intent").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("getInfoForIntent",t)}async getInfoForIntentsByContext(t){this.wire.sendAction("interop-client-get-info-for-intents-by-context").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("getInfoForIntentsByContext",t)}async fireIntentForContext(t){this.wire.sendAction("interop-client-fire-intent-for-context").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("fireIntentForContext",t)}async joinSessionContextGroup(t){try{const e=Mn(this,xn,"f").get(t);if(e)return e.getUserInstance();const n=await Mn(this,bn,"f"),{hasConflict:i}=await n.dispatch("sessionContextGroup:createIfNeeded",{sessionContextGroupId:t});i&&console.warn(`A (non-session) context group with the name "${t}" already exists. If you are trying to join a Context Group, call joinContextGroup instead.`);const r=new mn(this.wire,Mn(this,bn,"f"),t);return Mn(this,xn,"f").set(t,r),r.getUserInstance()}catch(e){throw console.error(`Error thrown trying to create Session Context Group with id "${t}": ${e}`),e}}async onDisconnection(t){this.wire.sendAction("interop-client-add-ondisconnection-listener").catch(t=>{});return(await Mn(this,bn,"f")).onDisconnection(e=>{const{uuid:n}=e;t({type:"interop-broker",topic:"disconnected",brokerName:n})})}getFDC3Sync(t){return Mn(this,An,"f").call(this,t,this,this.wire)}async getFDC3(t){return this.getFDC3Sync(t)}static async ferryFdc3Call(t,e,n){return(await Mn(t,bn,"f")).dispatch(e,n||null)}}function kn(t,e){if(e&&"2.0"===e){const e=function(t){return["fdc3HandleFindInstances","handleInfoForIntent","handleInfoForIntentsByContext","fdc3HandleGetAppMetadata","fdc3HandleGetInfo","fdc3HandleOpen","handleFiredIntent","handleFiredIntentForContext"].filter(e=>t[e]===on.prototype[e])}(t);e.length>0&&console.warn(`WARNING: FDC3 2.0 has been set as a default option for Views in this Platform, but the required InteropBroker APIs for FDC3 2.0 compliance have not all been overridden.\nThe following APIs need to be overridden:\n${e.join("\n")}`)}}bn=new WeakMap,xn=new WeakMap,An=new WeakMap,En=new WeakMap;class Tn{constructor(t,e){this.id=e,this.client=t,this.listeners=new Map}async broadcast(t){return this.client.dispatch("broadcast",{context:t})}async getCurrentContext(t){return this.client.dispatch("getCurrentContext",{contextType:t})}async addContextListener(t,e){if("function"!=typeof e)throw new Error("Non-function argument passed to the second parameter 'handler'. Be aware that the argument order does not match the FDC3 standard.");let n;n=t?`contextHandler:invoke-${this.id}-${t}-${De()}`:`contextHandler:invoke-${this.id}-${De()}`,this.client.register(n,Ue(e,n));const i={unsubscribe:await this.createContextUnsubscribeCb(n)};return this.listeners.set(n,i),await this.client.dispatch("contextHandlerAdded",{handlerId:n,contextType:t}),i}createNonStandardUnsubscribeCb(t){return async()=>{this.client.remove(t),this.listeners.delete(t),await this.client.dispatch("nonStandardHandlerRemoved",{handlerId:t})}}createContextUnsubscribeCb(t){return async()=>{this.client.remove(t),this.listeners.delete(t),await this.client.dispatch("contextHandlerRemoved",{handlerId:t})}}onAddContextListener(t){const e=`onContextHandlerAdded:invoke-${this.id}-${De()}`;this.client.register(e,t);const n={unsubscribe:this.createNonStandardUnsubscribeCb(e)};return this.listeners.set(e,n),this.client.dispatch("onAddContextHandlerAdded",{handlerId:e}),n}onDisconnect(t){const e=`onDisconnect:invoke-${this.id}-${De()}`;this.client.register(e,t);const n={unsubscribe:this.createNonStandardUnsubscribeCb(e)};return this.listeners.set(e,n),this.client.dispatch("onDisconnectHandlerAdded",{handlerId:e}),n}onUnsubscribe(t){const e=`onUnsubscribe:invoke-${this.id}-${De()}`;this.client.register(e,t);const n={unsubscribe:this.createNonStandardUnsubscribeCb(e)};return this.listeners.set(e,n),this.client.dispatch("onUnsubscribeHandlerAdded",{handlerId:e}),n}async cleanUpAllSubs(){Array.from(this.listeners.keys()).forEach(t=>{this.client.remove(t),this.listeners.delete(t)})}async disconnect(){try{await this.client.dispatch("clientDisconnecting"),await this.cleanUpAllSubs(),await this.client.disconnect()}catch(t){throw new Error(t.message)}}}const Ln=t=>({id:t.id,type:"app",broadcast:t.setContext,getCurrentContext:async e=>{const n=await t.getCurrentContext(e);return void 0===n?null:n},addContextListener:(n,i)=>{let r,s;"function"==typeof n?(console.warn("addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)"),r=n):(r=i,"string"==typeof n&&(s=n));const o=(async()=>{let n=!0;const i=await t.getCurrentContext(s);return t.addContextHandler((t,s)=>{if(!n||(n=!1,!e(i,t)))return r(t,s)},s)})();return{...o,unsubscribe:()=>o.then(t=>t.unsubscribe())}}}),$n=t=>{const e=Ln(t);return{...e,addContextListener:async(...t)=>e.addContextListener(...t)}},Fn=t=>({addContextListener:()=>{throw new Gn("Channel.addContextListener",t)},broadcast:()=>{throw new Gn("Channel.broadcast",t)},getCurrentContext:()=>{throw new Gn("Channel.getCurrentContext",t)}});class Gn extends Error{constructor(t,e="System"){super(t),this.message=`Calling ${t} on an instance of a ${e} Channel returned by fdc3.get${e}Channels is not supported. If you would like to use a ${e} Channel, please use fdc3.joinChannel, fdc3.addContextListener, and fdc3.broadcast instead.`}}var Rn,On;!function(t){t.NoResultReturned="NoResultReturned",t.IntentHandlerRejected="IntentHandlerRejected"}(Rn||(Rn={})),function(t){t.NoChannelFound="NoChannelFound",t.AccessDenied="AccessDenied",t.CreationFailed="CreationFailed"}(On||(On={}));const Wn=t=>{let e=!1;const n=()=>{if(e)throw new Error("Private Channel Client has been disconnected from the Private Channel")};return{id:t.id,type:"private",broadcast:async e=>(n(),t.broadcast(e)),getCurrentContext:async e=>(n(),t.getCurrentContext(e)),addContextListener:async(e,i)=>{n();let r=i,s=e;"function"==typeof e&&(console.warn("addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)"),r=e,s=null);return t.addContextListener(s,r)},onAddContextListener:e=>(n(),t.onAddContextListener(e)),disconnect:async()=>(n(),e=!0,t.disconnect()),onDisconnect:e=>(n(),t.onDisconnect(e)),onUnsubscribe:e=>(n(),t.onUnsubscribe(e))}},jn=async(t,e,n,i)=>{const r=De(),s=n?{target:n,intentResolutionResultId:r}:{intentResolutionResultId:r},o=i?{name:i,context:e,metadata:s}:{...e,metadata:s},a=new Promise((e,n)=>{fin.InterApplicationBus.subscribe({uuid:"*"},r,t=>{e(t)}).catch(()=>{"other"===t.wire.environment.type&&e(void 0),n(new Error("getResult is not supported in this environment"))})}),c=async()=>{let e=await a;if(null==e)return;if("object"!=typeof e)throw new Error(Rn.NoResultReturned);const{error:n}=e;if(n)throw new Error(Rn.IntentHandlerRejected);if((t=>{if(t&&"object"==typeof t&&"type"in t&&"id"in t){const{type:e,id:n}=t;return"string"==typeof e&&"string"==typeof n&&("app"===e||"private"===e)}return!1})(e)){const{id:n,type:i}=e;switch(i){case"private":e=await(async t=>{try{const e=await fin.InterApplicationBus.Channel.connect(t),n=new Tn(e,t);return Wn(n)}catch(e){throw new Error(`Private Channel with id: ${t} doesn't exist`)}})(n);break;case"app":{const i=await t.joinSessionContextGroup(n);e=$n(i);break}}}else if(!(t=>{if(t&&"object"==typeof t&&"type"in t){const{type:e}=t;return"string"==typeof e}return!1})(e))throw new Error(Rn.NoResultReturned);return e},d=i?await t.fireIntent(o):await t.fireIntentForContext(o);return"object"!=typeof d?{source:{appId:"",instanceId:""},intent:"",version:"2.0",getResult:c}:{...d,getResult:c}};var Nn,Hn=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)},Bn=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n};class Dn{get client(){return Hn(this,Nn,"f").call(this)}get fin(){return this.wire.getFin()}constructor(t,e){this.wire=e,Nn.set(this,void 0),Bn(this,Nn,t,"f")}async broadcast(t){return this.wire.recordAnalytic("fdc3-broadcast"),this.client.setContext(t)}async _open(t,e){this.wire.recordAnalytic("fdc3-open");try{return await Sn.ferryFdc3Call(this.client,"fdc3Open",{app:t,context:e})}catch(t){const e=t.message===qe.fdc3Open?"ResolverUnavailable":t.message;throw new Error(e)}}async _getChannels(){return(await this.client.getContextGroups()).map(t=>({...t,type:"system",...Fn()}))}async getOrCreateChannel(t,e){this.wire.recordAnalytic("fdc3-get-or-create-channel");if(await Sn.ferryFdc3Call(this.client,"isIdUsedByPrivateChannel",{channelId:t}))throw new Error(On.AccessDenied);const n=(await this._getChannels()).find(e=>e.id===t);if(n)return{...n,type:"system",...Fn()};try{return e(await this.client.joinSessionContextGroup(t))}catch(t){throw console.error(t.message),new Error(On.CreationFailed)}}async getSystemChannels(){return this.wire.recordAnalytic("fdc3-get-system-channels"),this._getChannels()}async joinChannel(t){this.wire.recordAnalytic("fdc3-join-channel");try{if(!await this.client.getInfoForContextGroup(t))throw console.error(`No User Channel was found with the ID "${t}". If this is an App Channel, use getOrCreateChannel instead.`),new Error(On.NoChannelFound);return await this.client.joinContextGroup(t)}catch(t){if(t.message===On.NoChannelFound)throw new Error(On.NoChannelFound);if(console.error(t.message),t.message.startsWith("Attempting to join a context group that does not exist"))throw new Error(On.NoChannelFound);throw new Error(On.AccessDenied)}}async getCurrentChannel(){this.wire.recordAnalytic("fdc3-get-current-channel");const t=await this.getCurrentContextGroupInfo();return t?this.buildChannelObject(t):null}async leaveCurrentChannel(){return this.wire.recordAnalytic("fdc3-leave-current-channel"),this.client.removeFromContextGroup()}async getCurrentContextGroupInfo(){const t=await this.client.getContextGroups(),e=t.map(async t=>this.client.getAllClientsInContextGroup(t.id));return t[(await Promise.all(e)).findIndex(t=>t.some(t=>{const{uuid:e,name:n}=t;return this.wire.me.uuid===e&&this.wire.me.name===n}))]}async buildChannelObject(t){return{...t,type:"system",addContextListener:(...[t,n])=>{let i,r;"function"==typeof t?(console.warn("addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)"),i=t):(i=n,"string"==typeof t&&(r=t));const s=(async()=>{let t=!0;const n=await this.client.getCurrentContext(r);return this.client.addContextHandler((r,s)=>{if(!t||(t=!1,!e(n,r)))return i(r,s)},r)})();return{...s,unsubscribe:()=>s.then(t=>t.unsubscribe())}},broadcast:this.broadcast.bind(this),getCurrentContext:async t=>{const e=await this.client.getCurrentContext(t);return void 0===e?null:e}}}}Nn=new WeakMap;class Vn extends Dn{async open(t,e){await super._open(t,e)}addContextListener(t,e){let n;return this.wire.recordAnalytic("fdc3-add-context-listener"),"function"==typeof t?(console.warn("addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)"),n=this.client.addContextHandler(t)):n=this.client.addContextHandler(e,null===t?void 0:t),{...n,unsubscribe:()=>n.then(t=>t.unsubscribe())}}addIntentListener(t,e){this.wire.recordAnalytic("fdc3-add-intent-listener");const n=this.client.registerIntentHandler(t=>{const{context:n,metadata:i}=t,{metadata:r}=n,s=i?.intentResolutionResultId||r?.intentResolutionResultId;s&&this.fin.InterApplicationBus.publish(s,null).catch(()=>null),e(t.context)},t,{fdc3Version:"1.2"});return{...n,unsubscribe:()=>n.then(t=>t.unsubscribe())}}async raiseIntent(t,e,n){this.wire.recordAnalytic("fdc3-raise-intent");const i=n?{name:t,context:e,metadata:{target:n}}:{name:t,context:e};try{return await this.client.fireIntent(i)}catch(t){const e=t.message===qe.fireIntent?"ResolverUnavailable":t.message;throw new Error(e)}}async findIntent(t,e){this.wire.recordAnalytic("fdc3-find-intent");try{return await this.client.getInfoForIntent({name:t,context:e})}catch(t){const e=t.message===qe.getInfoForIntent?"ResolverUnavailable":t.message;throw new Error(e)}}async findIntentsByContext(t){this.wire.recordAnalytic("fdc3-find-intents-by-context");try{return await this.client.getInfoForIntentsByContext(t)}catch(t){const e=t.message===qe.getInfoForIntentsByContext?"ResolverUnavailable":t.message;throw new Error(e)}}async raiseIntentForContext(t,e){this.wire.recordAnalytic("fdc3-raise-intent-for-context");try{return await this.client.fireIntentForContext({...t,metadata:{target:e}})}catch(t){const e=t.message===qe.fireIntentForContext?"ResolverUnavailable":t.message;throw new Error(e)}}async getOrCreateChannel(t){return super.getOrCreateChannel(t,Ln)}getInfo(){this.wire.recordAnalytic("fdc3-get-info");return{providerVersion:this.wire.environment.getAdapterVersionSync(),provider:`openfin-${this.wire.me.uuid}`,fdc3Version:"1.2"}}}class Un extends Dn{async open(t,e){return"string"==typeof t&&console.warn("Passing a string as the app parameter is deprecated, please use an AppIdentifier ({ appId: string; instanceId?: string })."),super._open(t,e)}async findInstances(t){this.wire.recordAnalytic("fdc3-find-instances");try{return await Sn.ferryFdc3Call(this.client,"fdc3FindInstances",t)}catch(t){const e=t.message===qe.fdc3FindInstances?"ResolverUnavailable":t.message;throw new Error(e)}}async getAppMetadata(t){this.wire.recordAnalytic("fdc3-get-app-metadata");try{return await Sn.ferryFdc3Call(this.client,"fdc3GetAppMetadata",t)}catch(t){const e=t.message===qe.fdc3GetAppMetadata?"ResolverUnavailable":t.message;throw new Error(e)}}async addContextListener(t,e){this.wire.recordAnalytic("fdc3-add-context-listener");const n=t=>e=>{const{contextMetadata:n,...i}=e,r=n?[{...i},n]:[e,null];t(...r)};let i=e,r=n(i);return"function"==typeof t?(console.warn("addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)"),i=t,r=n(i),this.client.addContextHandler(r)):this.client.addContextHandler(r,null===t?void 0:t)}async findIntent(t,e,n){this.wire.recordAnalytic("fdc3-find-intent");try{return await this.client.getInfoForIntent({name:t,context:e,metadata:{resultType:n}})}catch(t){const e=t.message===qe.getInfoForIntent?"ResolverUnavailable":t.message;throw new Error(e)}}async findIntentsByContext(t,e){this.wire.recordAnalytic("fdc3-find-intents-by-context");const n=e?{context:t,metadata:{resultType:e}}:t;try{return await Sn.ferryFdc3Call(this.client,"fdc3v2FindIntentsByContext",n)}catch(t){const e=t.message===qe.getInfoForIntentsByContext?"ResolverUnavailable":t.message;throw new Error(e)}}async raiseIntent(t,e,n){this.wire.recordAnalytic("fdc3-raise-intent");try{return"string"==typeof n&&console.warn("Passing a string as the app parameter is deprecated, please use an AppIdentifier ({ appId: string; instanceId?: string })."),jn(this.client,e,n,t)}catch(t){const e=t.message===qe.fireIntent?"ResolverUnavailable":t.message;throw new Error(e)}}async raiseIntentForContext(t,e){this.wire.recordAnalytic("fdc3-raise-intent-for-context");try{return"string"==typeof e&&console.warn("Passing a string as the app parameter is deprecated, please use an AppIdentifier ({ appId: string; instanceId?: string })."),jn(this.client,t,e)}catch(t){const e=t.message===qe.fireIntent?"ResolverUnavailable":t.message;throw new Error(e)}}async addIntentListener(t,e){if(this.wire.recordAnalytic("fdc3-add-intent-listener"),"string"!=typeof t)throw new Error("First argument must be an Intent name");return this.client.registerIntentHandler(async t=>{let n,i;const{context:r,metadata:s}=t,{contextMetadata:o,metadata:a,...c}=r,d=s?.intentResolutionResultId||a?.intentResolutionResultId;try{const t=a?{metadata:a,...c}:{...c};n=await e(t,o),i=n}catch(t){n=t,i={error:!0}}if(d&&this.fin.InterApplicationBus.publish(d,i).catch(()=>null),n instanceof Error)throw new Error(n.message);return n},t,{fdc3Version:"2.0"})}async getOrCreateChannel(t){return super.getOrCreateChannel(t,$n)}async createPrivateChannel(){const t=De();await Sn.ferryFdc3Call(this.client,"createPrivateChannelProvider",{channelId:t});const e=await this.fin.InterApplicationBus.Channel.connect(t),n=new Tn(e,t);return Wn(n)}async getUserChannels(){return(await this.client.getContextGroups()).map(t=>({...t,type:"user",...Fn("User")}))}async getSystemChannels(){return console.warn("This API has been deprecated. Please use fdc3.getUserChannels instead."),super.getSystemChannels()}async joinUserChannel(t){return super.joinChannel(t)}async joinChannel(t){return console.warn("This API has been deprecated. Please use fdc3.joinUserChannel instead."),super.joinChannel(t)}async getCurrentChannel(){const t=await super.getCurrentChannel();return t?{...t,type:"user",broadcast:this.broadcast.bind(this)}:null}async getInfo(){return Sn.ferryFdc3Call(this.client,"fdc3v2GetInfo",{fdc3Version:"2.0"})}}const zn=(t,e,n)=>{switch(t){case"1.2":return new Vn(()=>e,n);case"2.0":return new Un(()=>e,n);default:throw new Error(`Invalid FDC3 version provided: ${t}. Must be '1.2' or '2.0'`)}},_n=t=>new t,qn="You have attempted to use or modify InteropBroker parameters, which is not allowed. You are likely using an older InteropBroker override scheme. Please consult our Interop docs for guidance on migrating to the new override scheme.";class Jn extends l{async init(t,e=_n){this.wire.recordAnalytic("interop-init");const n=await this.wire.environment.getInteropInfo(this.wire.getFin()),i=function(t){const e=()=>{throw new Error(t)};return new Proxy({},{apply:e,construct:e,defineProperty:e,deleteProperty:e,get:e,getOwnPropertyDescriptor:e,getPrototypeOf:e,has:e,isExtensible:e,ownKeys:e,preventExtensions:e,set:e,setPrototypeOf:e})}(qn),r=(s=qn,o=structuredClone(n),new Proxy(o,{get:(...t)=>(console.warn(s),Reflect.get(...t)),set:(...t)=>(console.warn(s),Reflect.set(...t)),getOwnPropertyDescriptor:(...t)=>(console.warn(s),Reflect.getOwnPropertyDescriptor(...t)),ownKeys:(...t)=>(console.warn(s),Reflect.ownKeys(...t))}));var s,o;const a=async()=>{throw new Error(qn)},c=on.createClosedConstructor(this.wire,()=>this.fin.InterApplicationBus.Channel.create(`interop-broker-${t}`),n);let d;if(Array.isArray(e)){d=new(function(...t){return e=>t.reduceRight((t,e)=>n=>e(t(n)),t=>t)(e)}(...e)(c))(i,a,r)}else d=await e(c,i,a,r);return kn(d,n.fdc3Version),d}connectSync(t,e){return this.wire.recordAnalytic("interop-connect-sync"),new Sn(this.wire,this.wire.environment.whenReady().then(()=>this.fin.InterApplicationBus.Channel.connect(`interop-broker-${t}`,{payload:e})),zn)}}const Yn=t=>`snapshot-source-provider-${t.uuid}`;var Kn,Zn,Qn,Xn,ti,ei=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},ni=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};const ii=new Map;class ri extends l{constructor(t,e){super(t),Kn.set(this,void 0),Zn.set(this,()=>(ii.has(this.identity.uuid)||ii.set(this.identity.uuid,{eventFired:null,clientPromise:null}),ii.get(this.identity.uuid))),Qn.set(this,()=>(ni(this,Zn,"f").call(this).clientPromise||(ni(this,Zn,"f").call(this).clientPromise=ni(this,Xn,"f").call(this)),ni(this,Zn,"f").call(this).clientPromise)),Xn.set(this,async()=>{const t=Yn(this.identity);try{ni(this,Zn,"f").call(this).eventFired||await ni(this,ti,"f").call(this);const e=await this.fin.InterApplicationBus.Channel.connect(t,{wait:!1});return e.onDisconnection(()=>{ni(this,Zn,"f").call(this).clientPromise=null,ni(this,Zn,"f").call(this).eventFired=null}),e}catch(t){throw ni(this,Zn,"f").call(this).clientPromise=null,new Error("The targeted SnapshotSource is not currently initialized. Await this object's ready() method.")}}),ti.set(this,async()=>{const t=Yn(this.identity);let e,n;const i=new Promise((t,i)=>{e=t,n=i});ni(this,Zn,"f").call(this).eventFired=i;const r=async i=>{try{i.channelName===t&&(e(),await this.fin.InterApplicationBus.Channel.removeListener("connected",r))}catch(t){n(t)}};await this.fin.InterApplicationBus.Channel.on("connected",r)}),ei(this,Kn,e,"f")}get identity(){return ni(this,Kn,"f")}async ready(){this.wire.recordAnalytic("snapshot-source-ready");try{await ni(this,Qn,"f").call(this)}catch(t){await ni(this,Zn,"f").call(this).eventFired}}async getSnapshot(){this.wire.recordAnalytic("snapshot-source-get-snapshot");const t=await ni(this,Qn,"f").call(this),e=await t.dispatch("get-snapshot");return(await e).snapshot}async applySnapshot(t){this.wire.recordAnalytic("snapshot-source-apply-snapshot");return(await ni(this,Qn,"f").call(this)).dispatch("apply-snapshot",{snapshot:t})}}Kn=new WeakMap,Zn=new WeakMap,Qn=new WeakMap,Xn=new WeakMap,ti=new WeakMap;class si extends l{async init(t){if(this.wire.recordAnalytic("snapshot-source-init"),"object"!=typeof t||"function"!=typeof t.getSnapshot||"function"!=typeof t.applySnapshot)throw new Error("you must pass in a valid SnapshotProvider");const e=await this.fin.InterApplicationBus.Channel.create(Yn(this.fin.me));e.register("get-snapshot",async()=>({snapshot:await t.getSnapshot()})),e.register("apply-snapshot",({snapshot:e})=>t.applySnapshot(e))}wrapSync(t){return this.wire.recordAnalytic("snapshot-source-wrap-sync"),new ri(this.wire,t)}async wrap(t){return this.wire.recordAnalytic("snapshot-source-wrap"),this.wrapSync(t)}}var oi,ai,ci,di,hi=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},li=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class pi{constructor(t,e){oi.set(this,void 0),ai.set(this,void 0),ci.set(this,void 0),di.set(this,new A(async()=>(await li(this,oi,"f").registerMessageHandler(t=>{if("notification-created"===t.action&&t.payload.managerId===li(this,ci,"f")){const{notificationId:e,properties:n,documentUrl:i,notificationIcon:r,badge:s,image:o}=t.payload;try{li(this,ai,"f")?.call(this,{properties:n,images:{image:o,icon:r,badge:s},url:i,notificationId:e})}catch(t){console.error("Failed to handle notification",t)}return!0}return!1}),!0))),this.setNotificationHandler=async t=>{await li(this,di,"f").getValue(),hi(this,ai,t,"f")},this.destroy=async()=>{await li(this,oi,"f").sendAction("destroy-notification-manager",{managerId:li(this,ci,"f")})},this.dispatch=async t=>{const{notificationId:e,type:n}=t;await li(this,oi,"f").sendAction("dispatch-notification-event",{notificationId:e,type:n})},hi(this,oi,t,"f"),hi(this,ci,e,"f")}}oi=new WeakMap,ai=new WeakMap,ci=new WeakMap,di=new WeakMap;class ui extends l{constructor(){super(...arguments),this.init=async()=>{const{payload:{data:{managerId:t}}}=await this.wire.sendAction("init-notification-manager");return new pi(this.wire,t)}}}var wi,yi,fi,gi=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},mi=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class vi{constructor(t){wi.set(this,void 0),yi.set(this,new Set),fi.set(this,null),this.get=()=>mi(this,wi,"f"),this.set=t=>{if(mi(this,wi,"f")!==t){gi(this,wi,t,"f");for(const t of[...mi(this,yi,"f")])try{t()}catch(t){setTimeout(()=>{throw t},0)}}},this.subscribe=t=>(mi(this,yi,"f").add(t),()=>{mi(this,yi,"f").delete(t)}),gi(this,wi,t,"f")}get readonly(){return mi(this,fi,"f")||gi(this,fi,{get:this.get,subscribe:this.subscribe},"f"),mi(this,fi,"f")}}wi=new WeakMap,yi=new WeakMap,fi=new WeakMap;var Ci,Ii,bi=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},xi=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class Ai{constructor(t){Ci.set(this,void 0),Ii.set(this,new vi([])),bi(this,Ci,t,"f")}get state(){return xi(this,Ii,"f").readonly}static activate(t){xi(t,Ci,"f").registerMessageHandler(e=>"chrome-browser-actions-update"===e?.action&&(xi(t,Ii,"f").set(e?.payload?.actions??[]),!0))}async getExtensionActions(){return(await xi(this,Ci,"f").sendAction("chrome-browser-get-extension-actions",{})).payload.data.actions}async invokeExtensionAction(t){await xi(this,Ci,"f").sendAction("chrome-browser-invoke-extension-action",t)}async hideActiveExtensionPopup(){await xi(this,Ci,"f").sendAction("chrome-browser-hide-active-extension-popup",{})}}Ci=new WeakMap,Ii=new WeakMap;class Ei{constructor(t,e){this.Actions=new Ai(t),e&&Ai.activate(this.Actions)}}class Pi extends t{constructor(t){super(),this.wire=t,this.System=new V(t),this.Window=new $(t),this.Application=new T(t),this.InterApplicationBus=new Qt(t),this.Clipboard=new Xt(t),this.ExternalApplication=new ee(t),this.Frame=new ie(t),this.GlobalHotkey=new re(t),this.Platform=new Ne(t,this.InterApplicationBus.Channel),this.View=new x(t),this.Interop=new Jn(t),this.SnapshotSource=new si(t),this.NotificationManager=new ui(t),this.ChromeBrowser=new Ei(t,"window"===t.me.entityType),t.registerFin(this),this.me=function(t){const{uuid:e,name:n,entityType:i}=t.me,r={setContext(){throw new Error(He)},addContextHandler(){throw new Error(He)},getContextGroups(){throw new Error(He)},joinContextGroup(){throw new Error(He)},removeFromContextGroup(){throw new Error(He)},getAllClientsInContextGroup(){throw new Error(He)},getInfoForContextGroup(){throw new Error(He)}},s="Interop API has not been instantiated. Either connection has failed or you have not declared interop in your config.",o={setContext(){throw new Error(s)},addContextHandler(){throw new Error(s)},getContextGroups(){throw new Error(s)},joinContextGroup(){throw new Error(s)},removeFromContextGroup(){throw new Error(s)},getAllClientsInContextGroup(){throw new Error(s)},getInfoForContextGroup(){throw new Error(s)}},a={eventNames:()=>{throw new Error(He)},emit:()=>{throw new Error(He)},listeners:()=>{throw new Error(He)},listenerCount:()=>{throw new Error(He)},on:()=>{throw new Error(He)},addListener:()=>{throw new Error(He)},once:()=>{throw new Error(He)},prependListener:()=>{throw new Error(He)},prependOnceListener:()=>{throw new Error(He)},removeListener:()=>{throw new Error(He)},removeAllListeners:()=>{throw new Error(He)}};switch(i){case"view":return Object.assign(new S(t,{uuid:e,name:n}),Be(i,e,n),{interop:o,isOpenFin:!0});case"window":return Object.assign(new L(t,{uuid:e,name:n}),Be(i,e,n),{interop:o,isOpenFin:!0});case"iframe":return Object.assign(new ne(t,{uuid:e,name:n}),Be(i,e,n),{interop:o,isOpenFin:!0});case"external connection":return Object.assign(new te(t,{uuid:e}),Be(i,e,n),{interop:o,isOpenFin:!1});default:return{...Be(i,e,n),...a,interop:r,isOpenFin:!1}}}(t),t.on("disconnected",()=>{this.emit("disconnected")})}}function Mi(t){return ki(t)&&"string"==typeof t.address}function Si(t){return Mi(t)&&"string"==typeof t.token}function ki(t){return"string"==typeof t.uuid}class Ti{constructor(){this.storage=new Map}hashKeys(t){return t.map(Li).join("/")}getOrCreate(e){const n=this.hashKeys(e);return this.storage.has(n)||this.storage.set(n,new t),this.storage.get(n)}has(t){return this.storage.has(this.hashKeys(t))}delete(t){const e=this.hashKeys(t);return this.storage.delete(e)}}function Li(t){return btoa(t)}class $i extends Ti{constructor(){super(...arguments),this.dispatchEvent=t=>{if(function(t){return"process-desktop-event"===t.action}(t)){const{payload:e}=t,n=function(t){const{topic:e}=t;if("frame"===e||"window"===e||"view"===e){const{uuid:n,name:i}=t;return[e,n,i]}if("application"===e){const{uuid:n}=t;return[e,n]}return[e]}(e);if(this.has(n))return this.getOrCreate(n).emit(e.type,e),!0}return!1}}}var Fi,Gi,Ri,Oi,Wi,ji,Ni,Hi=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},Bi=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class Di extends t{constructor(t,e,n){super(),Fi.add(this),this.wireListeners=new Map,this.topicRefMap=new Map,this.eventAggregator=new $i,this.messageHandlers=[this.eventAggregator.dispatchEvent],Gi.set(this,void 0),Ri.set(this,!0),Oi.set(this,new Map),Wi.set(this,void 0),ji.set(this,void 0),this.connectSync=()=>{Bi(this,Gi,"f").connectSync()},this.getPort=()=>Bi(this,Gi,"f").getPort(),Hi(this,Gi,t(this.onmessage.bind(this)),"f"),this.environment=e,Hi(this,Ri,!1!==n.apiDiagnostics,"f"),this.sendRaw=Bi(this,Gi,"f").send.bind(Bi(this,Gi,"f")),this.registerMessageHandler(this.handleMessage.bind(this)),Bi(this,Gi,"f").on("disconnected",()=>{for(const[,{handleNack:t}]of this.wireListeners)t({reason:"Remote connection has closed"});this.wireListeners.clear(),clearTimeout(Bi(this,Wi,"f")),Hi(this,Wi,void 0,"f"),Bi(this,Oi,"f").clear(),this.emit("disconnected")});const{uuid:i,name:r}=n,s=this.environment.getCurrentEntityType();this.me=Be(s,i,r)}getFin(){if(!Bi(this,ji,"f"))throw new Error("No Fin object registered for this transport");return Bi(this,ji,"f")}registerFin(t){if(Bi(this,ji,"f"))throw new Error("Fin object has already been registered for this transport");Hi(this,ji,t,"f")}recordAnalytic(t){if(Bi(this,Ri,"f")&&(Bi(this,Oi,"f").set(t,(Bi(this,Oi,"f").get(t)??0)+1),void 0===Bi(this,Wi,"f"))){const t=setTimeout(()=>Bi(this,Fi,"m",Ni).call(this),3e4);"object"==typeof t&&null!==t&&t.unref?.(),Hi(this,Wi,t,"f")}}shutdown(){return Bi(this,Gi,"f").shutdown()}async connect(t){if(function(t){return"object"==typeof t.receiver&&Si({...t,address:""})}(t))return await Bi(this,Gi,"f").connect(t.receiver),this.authorize(t);if(Si(t))return this.connectRemote(t);if(Mi(t))return this.connectByPort(t);if(function(t){return ki(t)&&function(t){return t.runtime&&"string"==typeof t.runtime.version}(t)}(t)){const e=await this.environment.retrievePort(t);return this.connectByPort({...t,address:`ws://localhost:${e}`})}}async connectRemote(t){return await Bi(this,Gi,"f").connect(new(this.environment.getWsConstructor())(t.address)),this.authorize(t)}async connectByPort(t){const{address:e,uuid:n}=t,i={...t,type:"file-token"},r=Bi(this,Gi,"f");await r.connect(new(this.environment.getWsConstructor())(t.address));const s=await this.sendAction("request-external-authorization",{uuid:n,type:"file-token"},!0);if("external-authorization-response"!==s.action)throw new y(s.action);return await this.environment.writeToken(s.payload.file,s.payload.token),this.authorize(i)}async authorize(t){const e=await this.sendAction("request-authorization",t,!0);if("authorization-response"!==e.action)throw new y(e.action);if(!0!==e.payload.success)throw new C(e.payload)}sendAction(t,e={},n=!1){let i=()=>{};const r=C.getCallSite(1),s=this.environment.getNextMessageId(),o=new Promise((o,a)=>{i=a;const c={action:t,payload:e,messageId:s},d=Bi(this,Gi,"f");return this.addWireListener(s,o,t=>this.nackHandler(t,a,r),n),d.send(c).catch(a)});return Object.assign(o,{cancel:i,messageId:s})}nackHandler(t,e,n){e("string"==typeof t?t:new C(t,n))}ferryAction(t){return new Promise((e,n)=>{const i=this.environment.getNextMessageId();t.messageId=i;const r=t=>{e(t.payload)};return Bi(this,Gi,"f").send(t).then(()=>this.addWireListener(i,r,t=>this.nackHandler(t,n),!1)).catch(n)})}registerMessageHandler(t){this.messageHandlers.push(t)}addWireListener(t,e,n,i){i?this.uncorrelatedListener=e:this.wireListeners.has(t)?n({reason:"Duplicate handler id",error:ht(new f(String(t)))}):this.wireListeners.set(t,{resolve:e,handleNack:n})}onmessage(t){for(const e of this.messageHandlers)e.call(null,t)}handleMessage(t){const e=t.correlationId||NaN;if("correlationId"in t){if(!this.wireListeners.has(e))return!1;{const{resolve:n,handleNack:i}=this.wireListeners.get(e);"ack"!==t.action?i({reason:"Did not receive ack action",error:ht(new g(t.action))}):"payload"in t?t.payload.success?n.call(null,t):i(t.payload):"string"==typeof t.reason?i(t):(console.warn("Received invalid response from core",t),i({reason:"invalid response shape",error:ht(new Error("Invalid response shape"))})),this.wireListeners.delete(e)}}else this.uncorrelatedListener&&this.uncorrelatedListener.call(null,t),this.uncorrelatedListener=()=>{};return!0}}Gi=new WeakMap,Ri=new WeakMap,Oi=new WeakMap,Wi=new WeakMap,ji=new WeakMap,Fi=new WeakSet,Ni=function(){if(Hi(this,Wi,void 0,"f"),0===Bi(this,Oi,"f").size)return;const t=Object.fromEntries(Bi(this,Oi,"f"));Bi(this,Oi,"f").clear(),this.sendAction("send-analytics-batch",{counts:t}).catch(()=>{})};const Vi=new Map([["debug",0],["info",1],["warn",2],["error",3],["none",4]]),Ui=t=>"string"==typeof t?t:t instanceof Error?t.stack||t.message:JSON.stringify(t);class zi{static setGlobalLogLevel(t){zi.LOG_LEVEL=t??"error"}static setCustomLogger(t){zi.customLogger=t}constructor(...t){this.scopes=t}log(t,...e){const n=Vi.get(t)??3;if((Vi.get(zi.LOG_LEVEL)??3)<=n){const r=[`[${(new Date).toISOString()}]`,...(i=this.scopes,i.map(t=>`[${t}]`)),...e];if(zi.customLogger){const e=r.map(Ui).join(" ");zi.customLogger[t](e)}else 1===n?console.log(...r):console[t](...r)}var i}warn(...t){this.log("warn",...t)}error(...t){this.log("error",...t)}info(...t){this.log("info",...t)}debug(...t){this.log("debug",...t)}static getLogger(...t){return new zi(...t)}getLogger(...t){return new zi(...this.scopes,...t)}}zi.LOG_LEVEL="error";const _i=zi.getLogger("@openfin/core-web/client"),qi=_i.getLogger("data-channel"),Ji=t=>`data-channel-${t.me.uuid}`,Yi=async(t,e)=>{const n=async n=>t.dispatch("page-title-updated",{data:{identity:e,title:n}}).catch(t=>{qi.warn("Failed to dispatch title change",t)});document.title&&await n(document.title),s(document.head,n);const i=async n=>t.dispatch("page-favicon-updated",{data:{identity:e,favicon:n}}).catch(t=>{qi.warn("Failed to dispatch favicon change",t)}),r=document.querySelector('link[rel~="icon"]')?.href;r&&await i(r),o(document.head,t=>{i(t)})};function Ki(t,e){if(!function(t){return"string"==typeof t}(t))throw new Error(`Property ${e} has invalid type. Expected string, got ${typeof t}.`)}const Zi="web-broker-ports-ready",Qi=_i.getLogger("get-web-interop-ports");function Xi(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)}function tr(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n}var er,nr,ir;"function"==typeof SuppressedError&&SuppressedError;class rr extends t{constructor(t,e){super(),er.set(this,void 0),nr.set(this,void 0),ir.set(this,!1),this.connectSync=()=>{Xi(this,ir,"f")||(Xi(this,nr,"f").addEventListener("message",t=>{t.data?.topic?.startsWith("wire-message")&&t.data.message&&Xi(this,er,"f").call(this,{...JSON.parse(t.data.message),ports:t.ports})}),Xi(this,nr,"f").start())},this.connect=async()=>{this.connectSync()},this.send=t=>(Xi(this,nr,"f").postMessage({topic:"wire-message",message:JSON.stringify(t)}),Promise.resolve()),this.shutdown=async()=>{Xi(this,nr,"f").close()},tr(this,er,t,"f"),tr(this,nr,e,"f")}getPort(){return Xi(this,nr,"f")}}er=new WeakMap,nr=new WeakMap,ir=new WeakMap;class sr{async getViewWindowIdentity(t,e){const{identity:n}=await t.View.wrapSync(e).getCurrentWindow();return n}async getInteropInfo(t){const e=await t.Application.getCurrentSync().getInfo().catch(()=>null),n=e?.initialOptions?.interopBrokerConfiguration??{};return{fdc3Version:e?function({manifest:t,initialOptions:e}){const n=t?.platform?.defaultViewOptions?.fdc3InteropApi??e.defaultViewOptions?.fdc3InteropApi;return["1.2","2.0"].includes(n??"")?n:void 0}(e):void 0,...n,fdc3Info:{providerVersion:await t.System.getVersion(),provider:"OpenFin"}}}}class or extends sr{constructor(){super(...arguments),this.type="other",this.getRandomId=()=>{const t=new Uint32Array(1);return window.crypto.getRandomValues(t)[0].toString(32)}}getAdapterVersionSync(){return""}observeBounds(t,e){throw new Error("Method not implemented.")}layoutAllowedInContext(t){return!1}initLayoutManager(t,e,n){throw new Error("Method not implemented.")}applyLayoutSnapshot(t,e,n){throw new Error("Method not implemented.")}createLayout(t,e){throw new Error("Method not implemented.")}destroyLayout(t,e){throw new Error("Method not implemented.")}resolveLayout(t,e){throw new Error("Method not implemented.")}initPlatform(...t){throw new Error("Method not implemented.")}writeToken(t,e){return Promise.resolve("")}retrievePort(t){throw new Error("Method not implemented.")}getNextMessageId(){return this.getRandomId()}createChildContent(t){throw new Error("Method not implemented.")}getWebWindow(t){throw new Error("Method not implemented.")}getCurrentEntityIdentity(){throw new Error("Method not implemented.")}getCurrentEntityType(){return"external connection"}raiseEvent(t,e){throw new Error("Method not implemented.")}getUrl(){return location.href}getDefaultChannelOptions(){return{create:{},connect:{}}}getRtcPeer(){return new RTCPeerConnection}getWsConstructor(){return WebSocket}whenReady(){return Promise.resolve()}}const ar=t=>"platform"in t&&void 0!==t.platform;var cr,dr;class hr extends or{constructor(t){super(),this.connectConfig=t,cr.set(this,void 0),dr.set(this,new A(async()=>import("./main-f276b092.js"))),ar(t)&&this.validatePlatformOptions(t)}getAdapterVersionSync(){return"0.46.82"}validatePlatformOptions({platform:t}){if(!("layoutSnapshot"in t))throw new Error("Platform options are missing layoutSnapshot. Please provide a layoutSnapshot in the platform options.");if("windows"in t||"windows"in t.layoutSnapshot)throw new Error("It appears you tried to call connect() with a snapshot object from an OpenFin desktop environment. Note that connect() expects to be called with a platform property with this structure: { platform: { layoutSnapshot } }. To get a layoutSnapshot of the expected structure, use fin.Platform.Layout.getCurrentLayoutManagerSync().getLayoutSnapshot() in v34+ in your desktop environment.");const{layouts:e}=t.layoutSnapshot;Object.entries(e).map(([t,e])=>{if("object"!=typeof e||null===e)throw new Error(`Invalid layout detected: layoutSnapshot.layouts.${t} must be an object.`);if(!("content"in e))throw new Error(`Invalid layout detected: layoutSnapshot.layouts.${t} must contain a 'content' property.`)})}async getInteropInfo(t){return{...{contextGroups:void 0,logging:{beforeAction:{enabled:!1},afterAction:{enabled:!1}}},fdc3Version:void 0,fdc3Info:{providerVersion:"0.46.82",provider:"OpenFin Web"}}}layoutAllowedInContext(t){return!0}async initLayoutManager(t,e,n){if(Xi(this,cr,"f"))throw new Error("Layout already initialized.");if(!ar(this.connectConfig))throw new Error("Platform options are missing from connection config.");const{WebLayoutEntryPoint:i}=await Xi(this,dr,"f").getValue();return tr(this,cr,new i(this.connectConfig),"f"),await Xi(this,cr,"f").initLayoutManager(t,e,n)}async applyLayoutSnapshot(t,e,n){Xi(this,cr,"f")?.applyLayoutSnapshot(t,e,n)}async createLayout(t,e){return Xi(this,cr,"f")?.createLayout(t,e)}async destroyLayout(t,e){return Xi(this,cr,"f")?.destroyLayout(t,e)}async getViewWindowIdentity(t,e){return Promise.resolve({uuid:e.uuid,name:e.uuid})}}cr=new WeakMap,dr=new WeakMap;const lr=()=>{const t=((t,e)=>{const n=new RegExp(`^${e}<(?<meta>.*)>$`).exec(t)?.groups?.meta;if(n)try{return JSON.parse(atob(n))}catch(t){throw new Error(`Failed to decode JSON from ${n}.`)}})(window.name,"of-frame");if(t)try{const{name:e,uuid:n,brokerUrl:i,providerId:r,contextGroup:s}=t;return Ki(i,"brokerUrl"),Ki(n,"uuid"),Ki(e,"name"),{identity:{name:e,uuid:n},brokerUrl:i,interopConfig:{providerId:r,currentContextGroup:s},isOfView:!0}}catch(t){throw new Error(`Unexpected error occurred when inferring platform information: ${t.stack}`)}},pr=()=>{const t=n();return{uuid:t,name:t}},ur=async t=>{if("enabled"===t.connectionInheritance){const e=await(async t=>{const e=lr();if(e){const{validateOptions:n=()=>!0}=t,{identity:i,...r}=e;if(!await n(r))throw new Error("Parent options were rejected by validateOptions.");return e}})(t);if(e)return e}if(!t.options){const e="enabled"===t.connectionInheritance?"Broker URL was not specified nor provided by a platform container.":"Connection inheritance is disabled but no options were provided.";throw new Error(e)}return{...t.options,identity:pr(),isOfView:!1}},wr=async t=>{try{zi.setGlobalLogLevel(t.logLevel),zi.setCustomLogger(t.logger),_i.info("Establishing connection",t);const{brokerUrl:e,identity:n,timeout:s,interopConfig:o,isOfView:a}=await ur(t),{workerPort:c,iframeBrokerPort:d}=await(async(t,e,n)=>{const{origin:r}=new URL(t),s=document.createElement("IFRAME");let o;s.style.display="none";try{return await new Promise((a,c)=>{const d=t=>{if(t.source===s.contentWindow&&t.data?.topic===`ack-${Zi}`){if(t.origin!==r)c(new Error(`Broker redirected to unexpected origin ${t.origin}, expected ${r}.`));else if(t.data.success){const[e,n]=t.ports;a({iframeBrokerPort:e,workerPort:n})}else c(new C(t.data));window.removeEventListener("message",d),clearTimeout(o)}};window.addEventListener("message",d),Qi.info(`Connecting to broker ${t}`),s.setAttribute("src",t),s.setAttribute("name",i(e,"of-broker")),document.body.appendChild(s),Qi.info("Iframe loaded, awaiting init message from iframe"),n&&(o=setTimeout(()=>{window.removeEventListener("message",d),document.body.removeChild(s),c(new Error("Worker did not initialize in time"))},n))})}catch(t){throw new Error(`Failed to initialise Fin Web Client. ${t.message}`,{cause:t})}})(e,n,s);_i.info("Successfully established connection to shared worker");const h={entityType:"external connection",...n};c.start(),d.start();const l=((t,e,n)=>{const i=new hr(t),r=new Di(t=>new rr(t,e),i,n);return r.connectSync(),new Pi(r)})(t,c,h);return a&&window.top&&!r(window,window.top)&&(t=>{const e={uuid:t.me.uuid,name:t.me.name};qi.debug("Data channel connecting..."),t.InterApplicationBus.Channel.connect(Ji(t)).then(async t=>{qi.debug("Data channel connected"),await Yi(t,e)}).catch(t=>{qi.warn("Failed to connect to data channel, some features may not work like title updates",t)})})(l),o?.providerId&&(l.me.interop=l.Interop.connectSync(o.providerId),o?.currentContextGroup&&l.me.interop.joinContextGroup(o.currentContextGroup).catch(t=>{_i.warn(`Error joining specified context group: ${o?.currentContextGroup}, continuing`,t)})),{...l,me:{...l.me,identity:{uuid:l.me.uuid,name:l.me.name}}}}catch(t){throw new Error(`An error occured during web-interop connection: ${t.message}`)}};export{A as L,Xi as _,Ee as a,tr as b,o as c,_i as d,i as e,zi as f,s as g,Ji as h,r as i,wr as j,we as r};
|
|
1
|
+
import{EventEmitter as t}from"events";import{isEqual as e}from"es-toolkit";import{v4 as n}from"uuid";const i=(t,e)=>`${e}<${btoa(JSON.stringify(t))}>`,r=(t,e)=>{try{return t.origin===e.origin}catch(t){return!1}},s=(t,e)=>{const n=new MutationObserver(n=>{let i=!1;n.forEach(t=>{"TITLE"!==t.target.parentNode?.nodeName&&"TITLE"!==t.target.nodeName?(t.removedNodes.forEach(t=>{"TITLE"!==t.nodeName&&"TITLE"!==t.parentNode?.nodeName||(i=!0)}),t.addedNodes.forEach(t=>{"TITLE"!==t.nodeName&&"TITLE"!==t.parentNode?.nodeName||(i=!0)})):i=!0});const r=t.querySelector("title")?.textContent??"";i&&e(r)});return n.observe(t,{childList:!0,subtree:!0,characterData:!0}),n},o=(t,e)=>{let n;const i=new MutationObserver(()=>{(()=>{const i=t.querySelector('link[rel~="icon"]')?.href;i&&i!==n&&(n=i,e(i))})()});return i.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["href","rel"]}),i};var a,c,d=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},h=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class l{constructor(t){this.isNodeEnvironment=()=>"node"===this.wire.environment.type,this.isOpenFinEnvironment=()=>"openfin"===this.wire.environment.type,this.isBrowserEnvironment=()=>"other"===this.wire.environment.type,this.wire=t}get fin(){return this.wire.getFin()}get me(){return this.wire.me}}class p extends l{constructor(t,e,...n){super(t),this.topic=e,a.set(this,void 0),c.set(this,void 0),this.eventNames=()=>this.hasEmitter()?this.getOrCreateEmitter().eventNames():[],this.emit=(t,e,...n)=>!!this.hasEmitter()&&this.getOrCreateEmitter().emit(t,e,...n),this.hasEmitter=()=>this.wire.eventAggregator.has(h(this,a,"f")),this.getOrCreateEmitter=()=>this.wire.eventAggregator.getOrCreate(h(this,a,"f")),this.listeners=t=>this.hasEmitter()?this.getOrCreateEmitter().listeners(t):[],this.listenerCount=t=>this.hasEmitter()?this.getOrCreateEmitter().listenerCount(t):0,this.registerEventListener=async(t,e={},n,i)=>{const r={...this.identity,timestamp:e.timestamp||Date.now(),topic:this.topic,type:t},s=this.getOrCreateEmitter();n(s);try{await this.wire.sendAction("subscribe-to-desktop-event",r)}catch(t){throw i(s),this.deleteEmitterIfNothingRegistered(s),t}},this.deregisterEventListener=async(t,e={})=>{if(this.hasEmitter()){const n={...this.identity,timestamp:e.timestamp||Date.now(),topic:this.topic,type:t};return await this.wire.sendAction("unsubscribe-to-desktop-event",n).catch(()=>null),this.getOrCreateEmitter()}return Promise.resolve()},d(this,a,[e,...n],"f"),d(this,c,new WeakMap,"f")}async on(t,e,n){return await this.registerEventListener(t,n,n=>{n.on(t,e)},n=>{n.removeListener(t,e)}),this}async addListener(t,e,n){return this.on(t,e,n)}async once(t,e,n){const i=()=>this.deregisterEventListener(t);return h(this,c,"f").set(e,i),await this.registerEventListener(t,n,n=>{n.once(t,i),n.once(t,e)},n=>{n.removeListener(t,i),n.removeListener(t,e)}),this}async prependListener(t,e,n){return await this.registerEventListener(t,n,n=>{n.prependListener(t,e)},n=>{n.removeListener(t,e)}),this}async prependOnceListener(t,e,n){const i=()=>this.deregisterEventListener(t);return h(this,c,"f").set(e,i),await this.registerEventListener(t,n,n=>{n.prependOnceListener(t,e),n.once(t,i)},n=>{n.removeListener(t,e),n.removeListener(t,i)}),this}async removeListener(t,e,n){const i=await this.deregisterEventListener(t,n);if(i){i.removeListener(t,e);const n=h(this,c,"f").get(e);n&&i.removeListener(t,n),this.deleteEmitterIfNothingRegistered(i)}return this}async deregisterAllListeners(t){const e={...this.identity,type:t,topic:this.topic};if(this.hasEmitter()){const t=this.getOrCreateEmitter(),n=t.listenerCount(e.type),i=[];for(let t=0;t<n;t++)i.push(this.wire.sendAction("unsubscribe-to-desktop-event",e).catch(()=>null));return await Promise.all(i),t}}async removeAllListeners(t){const e=async t=>{const e=await this.deregisterAllListeners(t);e&&(e.removeAllListeners(t),this.deleteEmitterIfNothingRegistered(e))};if(t)await e(t);else if(this.hasEmitter()){const t=this.getOrCreateEmitter().eventNames();await Promise.all(t.map(e))}return this}deleteEmitterIfNothingRegistered(t){0===t.eventNames().length&&this.wire.eventAggregator.delete(h(this,a,"f"))}}a=new WeakMap,c=new WeakMap;const u=Error;function w(t,e){const n=t.split("\n").filter(t=>t.length>0),i=void 0===n[0]||(r=n[0],/^\s*at\s/.test(r)||r.includes("@"))?0:1;var r;return n.slice(i+e)}class y extends Error{}class f extends Error{}class g extends Error{}class m extends Error{}class v extends Error{constructor(t){const{message:e,name:n,stack:i,...r}=t;super(e),"cause"in t&&t.cause&&(this.cause=new v(t.cause)),this.name=n||"Error",this.stack=i??this.toString(),Object.keys(r).filter(t=>"cause"!==t).forEach(t=>{this[t]=r[t]})}}class C extends Error{static trimEndCallSites(t,e){const n=u.stackTraceLimit,i=u.prepareStackTrace;u.prepareStackTrace=(t,e)=>e;const r="string"==typeof t.stack,s=(r?t.stack?.split("\n"):t.stack)??[];if(u.prepareStackTrace=i,u.stackTraceLimit=n,s.length){const n=[];for(const t of r?s:s.slice(1))if(n.push(t),e.test(t.toString()))break;t.stack=r?n.join("\n"):C.prepareStackTrace(t,n)}}static getCallSite(t=0){const e=u.stackTraceLimit,n=t+1,i="number"==typeof e&&Number.isFinite(e)?e:10,r=u.prepareStackTrace;try{u.stackTraceLimit=i+n,u.prepareStackTrace=(t,e)=>e;const t=(new Error).stack;return Array.isArray(t)?t.slice(n):"string"==typeof t&&t.length>0?w(t,n):[]}finally{u.prepareStackTrace=r,u.stackTraceLimit=e}}static prepareStackTrace(t,e){const n=`${t.name||"Error"}: ${t.message||""}`,i="string"==typeof e?w(e,0):e;if(!Array.isArray(i)||0===i.length)return n;if(function(t){if(!Array.isArray(t)||0===t.length)return Array.isArray(t);const e=t[0];return"object"==typeof e&&null!==e&&"function"==typeof e.getFileName}(i)){const e=u.prepareStackTrace;return"function"==typeof e?e(t,i):`${n}\n${i.map(t=>` at ${t}`).join("\n")}`}return`${n}\n${i.join("\n")}`}constructor(t,e){const{reason:n,error:i}=t;super(n),this.name=this.constructor.name,i?.stack&&(this.cause=new v(i)),e&&(this.stack=C.prepareStackTrace(this,e))}}function I(t){let e;return"object"==typeof t&&"string"==typeof t.uuid||(e="Not a valid identity object"),e}const b=t=>{(t.contentNavigation?.whitelist||t.contentNavigation?.blacklist||t.contentRedirect?.whitelist||t.contentRedirect?.blacklist)&&console.warn("The properties 'whitelist' and 'blacklist' have been marked as deprecated and will be removed in a future version. Please use 'allowlist' and 'denylist'.")};class x extends l{async create(t){const{uuid:e}=this.wire.me;if(!t.name||"string"!=typeof t.name)throw new Error("Please provide a name property as a string in order to create a View.");return b(t),this.wire.environment.childViews?await this.wire.environment.createChildContent({entityType:"view",options:{...t,uuid:e}}):await this.wire.sendAction("create-view",{...t,uuid:e}),this.wrapSync({uuid:e,name:t.name})}async wrap(t){this.wire.recordAnalytic("view-wrap");const e=I(t);if(e)throw new Error(e);return new S(this.wire,t)}wrapSync(t){this.wire.recordAnalytic("view-wrap-sync");const e=I(t);if(e)throw new Error(e);return new S(this.wire,t)}getCurrent(){if(this.wire.recordAnalytic("view-get-current"),!this.wire.me.isView)throw new Error("You are not in a View context");const{uuid:t,name:e}=this.wire.me;return this.wrap({uuid:t,name:e})}getCurrentSync(){if(this.wire.recordAnalytic("view-get-current-sync"),!this.wire.me.isView)throw new Error("You are not in a View context");const{uuid:t,name:e}=this.wire.me;return this.wrapSync({uuid:t,name:e})}}class A{constructor(t){this.producerFn=t}getValue(){return this.value||(this.value=this.producerFn()),this.value}}class E{constructor(t){this.producerFn=t}async getValue(){return this.promise||(this.promise=this.producerFn().catch(t=>{throw delete this.promise,t})),this.promise}}class P extends p{constructor(t,e,n){super(t,n,e.uuid,e.name),this.identity=e,this.entityType=n}capturePage(t){return this.wire.sendAction("capture-page",{options:t,...this.identity}).then(({payload:t})=>t.data)}executeJavaScript(t){return this.wire.sendAction("execute-javascript-in-window",{...this.identity,code:t}).then(({payload:t})=>t.data)}getZoomLevel(){return this.wire.sendAction("get-zoom-level",this.identity).then(({payload:t})=>t.data)}setZoomLevel(t){return this.wire.sendAction("set-zoom-level",{...this.identity,level:t}).then(()=>{})}async translatePage(t){await this.wire.sendAction("translate-page",{...this.identity,...t})}async revertTranslation(){await this.wire.sendAction("revert-translation",this.identity)}async getTranslationState(){const{payload:t}=await this.wire.sendAction("get-translation-state",this.identity);return t.data}navigate(t){return this.wire.sendAction("navigate-window",{...this.identity,url:t}).then(()=>{})}navigateBack(){return this.wire.sendAction("navigate-window-back",{...this.identity}).then(()=>{})}async navigateForward(){await this.wire.sendAction("navigate-window-forward",{...this.identity})}stopNavigation(){return this.wire.sendAction("stop-window-navigation",{...this.identity}).then(()=>{})}reload(t=!1){return this.wire.sendAction("reload-window",{ignoreCache:t,...this.identity}).then(()=>{})}print(t={}){return this.wire.sendAction("print",{...this.identity,options:t}).then(()=>{})}findInPage(t,e){return this.wire.sendAction("find-in-page",{...this.identity,searchTerm:t,options:e}).then(({payload:t})=>t.data)}stopFindInPage(t){return this.wire.sendAction("stop-find-in-page",{...this.identity,action:t}).then(()=>{})}getPrinters(){return this.wire.sendAction("get-printers",{...this.identity}).then(({payload:t})=>t.data)}async focus({emitSynthFocused:t}={emitSynthFocused:!0}){await this.wire.sendAction("focus-window",{emitSynthFocused:t,...this.identity})}async showDeveloperTools(){await this.wire.sendAction("show-developer-tools",this.identity)}async getProcessInfo(){const{payload:{data:t}}=await this.wire.sendAction("get-process-info",this.identity);return t}async getSharedWorkers(){return this.wire.sendAction("get-shared-workers",this.identity).then(({payload:t})=>t.data)}async inspectSharedWorker(){await this.wire.sendAction("inspect-shared-worker",{...this.identity})}async inspectSharedWorkerById(t){await this.wire.sendAction("inspect-shared-worker-by-id",{...this.identity,workerId:t})}async inspectServiceWorker(){await this.wire.sendAction("inspect-service-worker",{...this.identity})}async showPopupWindow(t){if(this.wire.recordAnalytic(`${this.entityType}-show-popup-window`),t?.onPopupReady){const e=async({popupName:e})=>{try{const n=this.fin.Window.wrapSync({uuid:this.fin.me.uuid,name:e});await t.onPopupReady(n)}catch(t){throw new Error(`Something went wrong during onPopupReady execution: ${t}`)}};await this.once("popup-ready",e)}const{payload:e}=await this.wire.sendAction("try-create-popup-window",{options:{...t,hasResultCallback:!!t?.onPopupResult,hasReadyCallback:!!t?.onPopupReady},...this.identity}),{data:{willOpen:n,options:i}}=e;n&&await this.fin.Window.create(i.initialOptions);if(t?.onPopupResult){const e=async e=>{await t.onPopupResult((t=>{const{name:e,uuid:n,result:i,data:r}=t,s={identity:{name:e,uuid:n},result:i};return r&&(s.data=r),s})(e))},n=async()=>{await this.removeListener("popup-result",e)};await this.on("popup-result",e),await this.once("popup-teardown",n)}const{payload:r}=await this.wire.sendAction("show-popup-window",{options:i,...this.identity});return r.data}async getScreenCapturePermission(){return(await this.wire.sendAction("get-screen-capture-permissions",this.identity)).payload.data}}var M;class S extends P{constructor(t,e){super(t,e,"view"),this.identity=e,M.set(this,new A(()=>this.fin.Platform.wrapSync(this.identity).getClient())),this.attach=async t=>{await this.wire.sendAction("attach-view",{target:t,...this.identity})},this.destroy=async()=>{await this.wire.sendAction("destroy-view",{...this.identity})},this.show=async()=>{await this.wire.sendAction("show-view",{...this.identity})},this.showAt=async(t,e={})=>{await this.wire.sendAction("show-view-at",{bounds:t,...this.identity,options:e})},this.bringToFront=async()=>{await this.wire.sendAction("bring-view-to-front",{...this.identity})},this.hide=async()=>{await this.wire.sendAction("hide-view",{...this.identity})},this.setBounds=async t=>{await this.wire.sendAction("set-view-bounds",{bounds:t,...this.identity})},this.getBounds=async()=>(await this.wire.sendAction("get-view-bounds",{...this.identity})).payload.data,this.getInfo=async()=>(await this.wire.sendAction("get-view-info",{...this.identity})).payload.data,this.getParentLayout=async()=>(this.wire.recordAnalytic("view-get-parent-layout"),this.fin.Platform.Layout.getLayoutByViewIdentity(this.identity)),this.getOptions=async()=>this.wire.sendAction("get-view-options",{...this.identity}).then(({payload:t})=>t.data),this.updateOptions=async t=>this.wire.sendAction("update-view-options",{options:t,...this.identity}).then(()=>{}),this.getCurrentWindow=async()=>{const{payload:{data:t}}=await this.wire.sendAction("get-view-window",{...this.identity});return new L(this.wire,t)},this.getCurrentStack=async()=>{this.wire.recordAnalytic("view-get-current-stack");try{return(await this.getParentLayout()).getStackByViewIdentity(this.identity)}catch(t){throw new C({reason:"This view does not belong to a stack.",error:t})}},this.triggerBeforeUnload=async()=>(await this.wire.sendAction("trigger-before-unload",{...this.identity})).payload.data,this.bindToElement=async t=>{if(!t)throw new Error("Element not found.");return this.wire.environment.observeBounds(t,async t=>this.setBounds(t))}}async focus({emitSynthFocused:t}={emitSynthFocused:!0}){const e=await this.getCurrentWindow();await e.focusedWebViewWasChanged(),await super.focus({emitSynthFocused:t})}}M=new WeakMap;class k extends p{constructor(t,e){super(t,"application",e.uuid),this.identity=e,this.getPerformanceStats=async(t={})=>{const{include:e,resources:n=!0,browser:i=!1}=t,r=await this.wire.sendAction("get-application-performance-stats",{...this.identity,...void 0!==e?{include:(t=>t.map(t=>t instanceof RegExp?{type:"regex",expression:t.source,flags:t.flags}:t))(e)}:{},resources:n,browser:i});return r.payload.data},this.window=new L(this.wire,{uuid:this.identity.uuid,name:this.identity.uuid})}windowListFromIdentityList(t){const e=[];return t.forEach(t=>{e.push(new L(this.wire,{uuid:t.uuid,name:t.name}))}),e}isRunning(){return this.wire.sendAction("is-application-running",this.identity).then(({payload:t})=>t.data)}async quit(t=!1){try{await this._close(t),await this.wire.sendAction("destroy-application",{force:t,...this.identity})}catch(t){if(!["Remote connection has closed","Could not locate the requested application"].some(e=>t.message.includes(e)))throw t}}async _close(t=!1){try{await this.wire.sendAction("close-application",{force:t,...this.identity})}catch(t){if(!t.message.includes("Remote connection has closed"))throw t}}close(t=!1){return console.warn("Deprecation Warning: Application.close is deprecated Please use Application.quit"),this.wire.recordAnalytic("application-close"),this._close(t)}getChildWindows(){return this.wire.sendAction("get-child-windows",this.identity).then(({payload:t})=>{const e=[];return t.data.forEach(t=>{e.push({uuid:this.identity.uuid,name:t})}),this.windowListFromIdentityList(e)})}getManifest(){return this.wire.sendAction("get-application-manifest",this.identity).then(({payload:t})=>t.data)}getParentUuid(){return this.wire.sendAction("get-parent-application",this.identity).then(({payload:t})=>t.data)}getShortcuts(){return this.wire.sendAction("get-shortcuts",this.identity).then(({payload:t})=>t.data)}async getViews(){const{payload:t}=await this.wire.sendAction("application-get-views",this.identity);return t.data.map(t=>new S(this.wire,t))}getZoomLevel(){return this.wire.sendAction("get-application-zoom-level",this.identity).then(({payload:t})=>t.data)}getWindow(){return this.wire.recordAnalytic("application-get-window"),Promise.resolve(this.window)}registerUser(t,e){return this.wire.sendAction("register-user",{userName:t,appName:e,...this.identity}).then(()=>{})}removeTrayIcon(){return this.wire.sendAction("remove-tray-icon",this.identity).then(()=>{})}restart(){return this.wire.sendAction("restart-application",this.identity).then(()=>{})}run(){return console.warn("Deprecation Warning: Application.run is deprecated Please use fin.Application.start"),this.wire.recordAnalytic("application-run"),this._run()}_run(t={}){return this.wire.sendAction("run-application",{manifestUrl:this._manifestUrl,opts:t,...this.identity}).then(()=>{})}scheduleRestart(){return this.wire.sendAction("relaunch-on-close",this.identity).then(()=>{})}async sendApplicationLog(){const{payload:t}=await this.wire.sendAction("send-application-log",this.identity);return t.data}async setJumpList(t){await this.wire.sendAction("set-jump-list",{config:t,...this.identity})}setTrayIcon(t){return this.wire.sendAction("set-tray-icon",{enabledIcon:t,...this.identity}).then(()=>{})}async setTrayIconToolTip(t){await this.wire.sendAction("set-tray-icon-tooltip",{...this.identity,toolTip:t})}setShortcuts(t){return this.wire.sendAction("set-shortcuts",{data:t,...this.identity}).then(()=>{})}async setShortcutQueryParams(t){await this.wire.sendAction("set-shortcut-query-args",{data:t,...this.identity})}setZoomLevel(t){return this.wire.sendAction("set-application-zoom-level",{level:t,...this.identity}).then(()=>{})}async setAppLogUsername(t){await this.wire.sendAction("set-app-log-username",{data:t,...this.identity})}getTrayIconInfo(){return this.wire.sendAction("get-tray-icon-info",this.identity).then(({payload:t})=>t.data)}hasTrayIcon(){return this.wire.sendAction("has-tray-icon",this.identity).then(({payload:t})=>t.data)}terminate(){return this.wire.sendAction("terminate-application",this.identity).then(()=>{})}wait(){return this.wire.sendAction("wait-for-hung-application",this.identity).then(()=>{})}getInfo(){return this.wire.sendAction("get-info",this.identity).then(({payload:t})=>t.data)}async getProcessInfo(){const{payload:{data:t}}=await this.wire.sendAction("application-get-process-info",this.identity);return t}async setFileDownloadLocation(t){const{name:e}=this.wire.me,n={uuid:this.identity.uuid,name:e};await this.wire.sendAction("set-file-download-location",{...n,downloadLocation:t})}async getFileDownloadLocation(){const{payload:{data:t}}=await this.wire.sendAction("get-file-download-location",this.identity);return t}async showTrayIconPopupMenu(t){const{name:e}=this.wire.me,n={uuid:this.identity.uuid,name:e},{payload:i}=await this.wire.sendAction("show-tray-icon-popup-menu",{...n,options:t});return i.data}async closeTrayIconPopupMenu(){const{name:t}=this.wire.me,e={uuid:this.identity.uuid,name:t};await this.wire.sendAction("close-tray-icon-popup-menu",{...e})}}class T extends l{async wrap(t){this.wire.recordAnalytic("wrap-application");const e=I(t);if(e)throw new Error(e);return new k(this.wire,t)}wrapSync(t){this.wire.recordAnalytic("wrap-application-sync");const e=I(t);if(e)throw new Error(e);return new k(this.wire,t)}async _create(t){return void 0===t.waitForPageLoad&&(t.waitForPageLoad=!1),void 0===t.autoShow&&void 0===t.isPlatformController&&(t.autoShow=!0),await this.wire.sendAction("create-application",t),this.wrap({uuid:t.uuid})}create(t){return console.warn("Deprecation Warning: fin.Application.create is deprecated. Please use fin.Application.start"),this.wire.recordAnalytic("application-create"),this._create(t)}async start(t){this.wire.recordAnalytic("start-application");const e=await this._create(t);return await this.wire.sendAction("run-application",{uuid:t.uuid}),e}async startManyManifests(t,e){return this.wire.sendAction("run-applications",{applications:t,opts:e}).then(()=>{})}getCurrent(){return this.wire.recordAnalytic("get-current-application"),this.wrap({uuid:this.wire.me.uuid})}getCurrentSync(){return this.wire.recordAnalytic("get-current-application-sync"),this.wrapSync({uuid:this.wire.me.uuid})}async startFromManifest(t,e){this.wire.recordAnalytic("application-start-from-manifest");const n=await this._createFromManifest(t);return await n._run(e),n}createFromManifest(t){return console.warn("Deprecation Warning: fin.Application.createFromManifest is deprecated. Please use fin.Application.startFromManifest"),this.wire.recordAnalytic("application-create-from-manifest"),this._createFromManifest(t)}_createFromManifest(t){return this.wire.sendAction("get-application-manifest",{manifestUrl:t}).then(({payload:t})=>{const e=t.data.platform?t.data.platform.uuid:t.data.startup_app.uuid;return this.wrap({uuid:e})}).then(e=>(e._manifestUrl=t,e))}}class L extends P{constructor(t,e){super(t,e,"window")}async createWindow(t){this.wire.recordAnalytic("window-create-window");const e=await(async(t,e,n=()=>!0,i)=>{let r,s,o;const a=new Promise((t,e)=>{r=t,s=e}),c=t=>{n(t)&&(clearTimeout(o),r(t))};return await t.on(e,c),i&&(o=setTimeout(()=>s(new Error("event timed out")),i)),a.finally(()=>{t.removeListener(e,c).catch(()=>null)}),{getValue:()=>a}})(this,"fire-constructor-callback");void 0===t.waitForPageLoad&&(t.waitForPageLoad=!1),void 0===t.autoShow&&(t.autoShow=!0),b(t);const n=this.wire.environment.createChildContent({entityType:"window",options:t}),[i]=await Promise.all([e.getValue(),n]);let r;const{success:s}=i,o=i.data,{message:a}=o;r=s?{httpResponseCode:o.httpResponseCode,apiInjected:o.apiInjected}:{message:o.message,networkErrorCode:o.networkErrorCode,stack:o.stack};const c={message:a,cbPayload:r,success:s};try{this.getWebWindow().fin.__internal_.openerSuccessCBCalled()}catch(t){}return c.success?this:Promise.reject(c)}getAllFrames(){return this.wire.sendAction("get-all-frames",this.identity).then(({payload:t})=>t.data)}activateAndFocus(t){return this.wire.sendAction("activate-window-and-focus",{winIdentity:this.identity,focusIdentity:t}).then(({payload:t})=>t.data)}getBounds(t){return this.wire.sendAction("get-window-bounds",{...this.identity,options:t}).then(({payload:t})=>t.data)}center(){return this.wire.sendAction("center-window",this.identity).then(()=>{})}blur(){return this.wire.sendAction("blur-window",this.identity).then(()=>{})}bringToFront(){return this.wire.sendAction("bring-window-to-front",this.identity).then(()=>{})}animate(t,e){return this.wire.sendAction("animate-window",{transitions:t,options:e,...this.identity}).then(()=>{})}hide(){return this.wire.sendAction("hide-window",this.identity).then(()=>{})}close(t=!1){return this.wire.sendAction("close-window",{force:t,...this.identity}).then(()=>{Object.setPrototypeOf(this,null)})}focusedWebViewWasChanged(){return this.wire.sendAction("focused-webview-changed",this.identity).then(()=>{})}getNativeId(){return this.wire.sendAction("get-window-native-id",this.identity).then(({payload:t})=>t.data)}async getCurrentViews(){const{payload:t}=await this.wire.sendAction("window-get-views",this.identity);return t.data.map(t=>new S(this.wire,t))}disableFrame(){return console.warn("Function is deprecated; use disableUserMovement instead."),this.wire.sendAction("disable-window-frame",this.identity).then(()=>{})}disableUserMovement(){return this.wire.sendAction("disable-window-frame",this.identity).then(()=>{})}enableFrame(){return console.warn("Function is deprecated; use enableUserMovement instead."),this.wire.sendAction("enable-window-frame",this.identity).then(()=>{})}enableUserMovement(){return this.wire.sendAction("enable-window-frame",this.identity).then(()=>{})}flash(){return this.wire.sendAction("flash-window",this.identity).then(()=>{})}stopFlashing(){return this.wire.sendAction("stop-flash-window",this.identity).then(()=>{})}getInfo(){return this.wire.sendAction("get-window-info",this.identity).then(({payload:t})=>t.data)}async getLayout(t){this.wire.recordAnalytic("window-get-layout");const e=await this.getOptions();if(!e.layout&&!e.layoutSnapshot)throw new Error("Window does not have a Layout");return this.fin.Platform.Layout.wrap(t??this.identity)}getOptions(){return this.wire.sendAction("get-window-options",this.identity).then(({payload:t})=>t.data)}getParentApplication(){return this.wire.recordAnalytic("window-get-parent-application"),Promise.resolve(new k(this.wire,this.identity))}getParentWindow(){return this.wire.recordAnalytic("window-get-parent-window"),Promise.resolve(new k(this.wire,this.identity)).then(t=>t.getWindow())}async getSnapshot(t){const e={area:t,...this.identity};console.warn("Window.getSnapshot has been deprecated, please use Window.capturePage");return(await this.wire.sendAction("get-window-snapshot",e)).payload.data}getState(){return this.wire.sendAction("get-window-state",this.identity).then(({payload:t})=>t.data)}getWebWindow(){return this.wire.recordAnalytic("window-get-web-window"),this.wire.environment.getWebWindow(this.identity)}isMainWindow(){return this.wire.recordAnalytic("window-is-main-window"),this.me.uuid===this.me.name}isShowing(){return this.wire.sendAction("is-window-showing",this.identity).then(({payload:t})=>t.data)}maximize(){return this.wire.sendAction("maximize-window",this.identity).then(()=>{})}minimize(){return this.wire.sendAction("minimize-window",this.identity).then(()=>{})}moveBy(t,e,n){return this.wire.sendAction("move-window-by",{deltaLeft:t,deltaTop:e,positioningOptions:n,...this.identity}).then(()=>{})}moveTo(t,e,n){return this.wire.sendAction("move-window",{left:t,top:e,positioningOptions:n,...this.identity}).then(()=>{})}resizeBy(t,e,n,i){return this.wire.sendAction("resize-window-by",{deltaWidth:Math.floor(t),deltaHeight:Math.floor(e),anchor:n,positioningOptions:i,...this.identity}).then(()=>{})}resizeTo(t,e,n,i){return this.wire.sendAction("resize-window",{width:Math.floor(t),height:Math.floor(e),anchor:n,positioningOptions:i,...this.identity}).then(()=>{})}restore(){return this.wire.sendAction("restore-window",this.identity).then(()=>{})}setAsForeground(){return this.wire.sendAction("set-foreground-window",this.identity).then(()=>{})}setBounds(t,e){return this.wire.sendAction("set-window-bounds",{...t,...this.identity,positioningOptions:e}).then(()=>{})}show(t=!1){return this.wire.sendAction("show-window",{force:t,...this.identity}).then(()=>{})}showAt(t,e,n=!1){return this.wire.sendAction("show-at-window",{force:n,left:Math.floor(t),top:Math.floor(e),...this.identity}).then(()=>{})}updateOptions(t){return"frame"in t&&console.warn("Deprecation Warning: Starting with version 45 it will not be possible to change the frame value after window has been created."),this.wire.sendAction("update-window-options",{options:t,...this.identity}).then(()=>{})}authenticate(t,e){return this.wire.sendAction("window-authenticate",{userName:t,password:e,...this.identity}).then(()=>{})}async showPopupMenu(t){const{payload:e}=await this.wire.sendAction("show-popup-menu",{options:t,...this.identity});return e.data}async closePopupMenu(){return this.wire.sendAction("close-popup-menu",{...this.identity}).then(()=>{})}async dispatchPopupResult(t){this.wire.recordAnalytic("window-dispatch-popup-result"),await this.wire.sendAction("dispatch-popup-result",{data:t,...this.identity})}async print(t={content:"self"}){switch(t.content){case void 0:case"self":return super.print(t);case"screenshot":return this.wire.sendAction("print-screenshot",this.identity).then(()=>{});case"views":return this.wire.sendAction("print-views",{...this.identity,options:t}).then(()=>{});default:return}}async showDownloadBubble(t){return this.wire.sendAction("show-download-bubble",{...this.identity,anchor:t}).then(()=>{})}async updateDownloadBubbleAnchor(t){return this.wire.sendAction("update-download-bubble-anchor",{...this.identity,anchor:t}).then(()=>{})}}class $ extends l{async wrap(t){this.wire.recordAnalytic("window-wrap");const e=I(t);if(e)throw new Error(e);return new L(this.wire,t)}wrapSync(t){this.wire.recordAnalytic("window-wrap-sync");const e=I(t);if(e)throw new Error(e);return new L(this.wire,t)}create(t){this.wire.recordAnalytic("create-window");return new L(this.wire,{uuid:this.me.uuid,name:t.name}).createWindow(t)}getCurrent(){if(this.wire.recordAnalytic("get-current-window"),!this.wire.me.isWindow)throw new Error("You are not in a Window context");const{uuid:t,name:e}=this.wire.me;return this.wrap({uuid:t,name:e})}getCurrentSync(){if(this.wire.recordAnalytic("get-current-window-sync"),!this.wire.me.isWindow)throw new Error("You are not in a Window context");const{uuid:t,name:e}=this.wire.me;return this.wrapSync({uuid:t,name:e})}}class F extends l{async getCategories(){const{payload:t}=await this.wire.sendAction("content-tracing-get-categories");return t.data}async startRecording(t){await this.wire.sendAction("content-tracing-start-recording",{options:t})}async stopRecording(){const{payload:t}=await this.wire.sendAction("content-tracing-stop-recording");return t.data}async getTraceBufferUsage(){const{payload:t}=await this.wire.sendAction("content-tracing-get-trace-buffer-usage");return t.data}}var G,R,O,W,j,N,H=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)},B=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n};const D=(t,e)=>e&&"object"==typeof e&&!Array.isArray(e)?Object.fromEntries(Object.entries(e).sort()):e;class V extends p{constructor(t){super(t,"system"),G.add(this),R.set(this,new Set),O.set(this,new Set),W.set(this,[]),j.set(this,!1),this.ContentTracing=new F(t)}sendExternalProcessRequest(t,e){return new Promise((n,i)=>{const r="external-process-exited";let s,o,a,c;"function"==typeof e.listener&&(a=t=>{const n=t||{};o={topic:"exited",uuid:n.processUuid||"",exitCode:n.exitCode||0},s===t.processUuid&&(e.listener(o),c.removeListener(r,a))},this.wire.me.name||(this.wire.me.name=this.wire.me.uuid),c=new L(this.wire,this.wire.me),c.on(r,a)),this.wire.sendAction(t,e).then(({payload:t})=>{s=t.data.uuid,n(t.data),o&&s===o.uuid&&(e.listener(o),c.removeListener(r,a))}).catch(t=>{c&&c.removeListener(r,a),i(t)})})}getVersion(){return this.wire.sendAction("get-version").then(({payload:t})=>t.data)}clearCache(t){return this.wire.sendAction("clear-cache",t).then(()=>{})}clearHTTPCache(){return this.wire.sendAction("clear-http-cache").then(()=>{})}clearCacheData(t){return this.wire.sendAction("clear-cache-data",t||{}).then(()=>{})}deleteCacheOnExit(){return this.wire.sendAction("delete-cache-request").then(()=>{})}exit(){return this.wire.sendAction("exit-desktop").then(()=>{})}async fetchManifest(t){const{payload:{data:e}}=await this.wire.sendAction("fetch-manifest",{manifestUrl:t});return e}flushCookieStore(){return this.wire.sendAction("flush-cookie-store").then(()=>{})}getAllWindows(){return this.wire.sendAction("get-all-windows").then(({payload:t})=>t.data)}getAllApplications(){return this.wire.sendAction("get-all-applications").then(({payload:t})=>t.data)}getCommandLineArguments(){return this.wire.sendAction("get-command-line-arguments").then(({payload:t})=>t.data)}async getCrashReporterState(){const{payload:{data:{diagnosticMode:t,isRunning:e}}}=await this.wire.sendAction("get-crash-reporter-state");return console.warn("diagnosticMode property is deprecated. It will be removed in a future version"),{diagnosticMode:t,diagnosticsMode:t,isRunning:e}}async startCrashReporter(t){const e=t,n={...e,diagnosticMode:e.diagnosticsMode||e.diagnosticMode},{payload:{data:{diagnosticMode:i,isRunning:r}}}=await this.wire.sendAction("start-crash-reporter",n);return{diagnosticMode:i,diagnosticsMode:i,isRunning:r}}getUniqueUserId(){return this.wire.sendAction("get-unique-user-id").then(({payload:t})=>t.data)}getEntityInfo(t,e){return this.wire.sendAction("get-entity-info",{uuid:t,name:e}).then(({payload:t})=>t.data)}getEnvironmentVariable(t){return this.wire.sendAction("get-environment-variable",{environmentVariables:t}).then(({payload:t})=>t.data)}getFocusedWindow(){return this.wire.sendAction("get-focused-window").then(({payload:t})=>t.data)}getFocusedContent(){return this.wire.sendAction("get-focused-content").then(({payload:t})=>t.data)}async isAppCertified(t){const{payload:{data:{certifiedInfo:e}}}=await this.wire.sendAction("is-app-certified",{manifestUrl:t});return e}getInstalledRuntimes(){return this.wire.sendAction("get-installed-runtimes").then(({payload:t})=>t.data.runtimes)}async getInstalledApps(){const{payload:{data:{installedApps:t}}}=await this.wire.sendAction("get-installed-apps");return t}getLog(t){return this.wire.sendAction("view-log",t).then(({payload:t})=>t.data)}getMachineId(){return this.wire.sendAction("get-machine-id").then(({payload:t})=>t.data)}getMinLogLevel(){return this.wire.sendAction("get-min-log-level").then(({payload:t})=>t.data)}getLogList(){return this.wire.sendAction("list-logs").then(({payload:t})=>t.data)}getMonitorInfo(){return this.wire.sendAction("get-monitor-info").then(({payload:t})=>t.data)}getMousePosition(){return this.wire.sendAction("get-mouse-position").then(({payload:t})=>t.data)}getProcessList(){return console.warn("System.getProcessList has been deprecated. Please consider using our new process APIs: Window.getProcessInfo, View.getProcessInfo, Application.getProcessInfo, System.getAllProcessInfo"),this.wire.sendAction("process-snapshot").then(({payload:t})=>t.data)}async getAllProcessInfo(){const{payload:{data:t}}=await this.wire.sendAction("get-all-process-info",this.identity);return t}getProxySettings(){return this.wire.sendAction("get-proxy-settings").then(({payload:t})=>t.data)}getRuntimeInfo(){return this.wire.sendAction("get-runtime-info").then(({payload:t})=>t.data)}getRvmInfo(){return this.wire.sendAction("get-rvm-info").then(({payload:t})=>t.data)}getHostSpecs(){return this.wire.sendAction("get-host-specs").then(({payload:t})=>t.data)}getOSInfo(){return this.wire.sendAction("get-os-info").then(({payload:t})=>t.data)}launchExternalProcess(t){return this.sendExternalProcessRequest("launch-external-process",t)}monitorExternalProcess(t){return this.sendExternalProcessRequest("monitor-external-process",t)}log(t,e,n){return this.wire.sendAction("write-to-log",{level:t,message:e,target:n??{}}).then(()=>{})}openUrlWithBrowser(t){return this.wire.sendAction("open-url-with-browser",{url:t}).then(()=>{})}async registerCustomProtocol(t){if("object"!=typeof t)throw new Error("Must provide an object with a `protocolName` property having a string value.");await this.wire.sendAction("register-custom-protocol",t)}async unregisterCustomProtocol(t){await this.wire.sendAction("unregister-custom-protocol",{protocolName:t})}async getCustomProtocolState(t){return this.wire.sendAction("get-custom-protocol-state",{protocolName:t}).then(({payload:t})=>t.data)}releaseExternalProcess(t){return this.wire.sendAction("release-external-process",{uuid:t}).then(()=>{})}showDeveloperTools(t){return this.wire.sendAction("show-developer-tools",t).then(()=>{})}terminateExternalProcess(t){return this.wire.sendAction("terminate-external-process",t).then(()=>{})}updateProxySettings(t){return this.wire.sendAction("update-proxy",t).then(()=>{})}async downloadAsset(t,e){const n=()=>{};let i=n,r=n;const s=new Promise((t,e)=>{i=t,r=e});if("openfin"!==this.wire.environment.type)throw new m("downloadAsset only supported in an OpenFin Render process");const o=C.getCallSite(),a=this.wire.environment.getNextMessageId().toString(),c=`asset-download-progress-${a}`,d=`asset-download-error-${a}`,h=`asset-download-complete-${a}`,l=t=>{const n={downloadedBytes:t.downloadedBytes,totalBytes:t.totalBytes};e(n)},p=()=>{this.removeListener(c,l)};await Promise.all([this.on(c,l),this.once(d,t=>{p();const{reason:e,err:n}=t;r(new C({reason:e,error:n},o))}),this.once(h,()=>{p(),i()})]);const u=Object.assign(t,{downloadId:a});return await this.wire.sendAction("download-asset",u).catch(t=>{throw p(),t}),s}downloadRuntime(t,e){const n=C.getCallSite();return new Promise((i,r)=>{if("openfin"!==this.wire.environment.type)return void r(new m("downloadRuntime only supported in an OpenFin Render process"));const s=this.wire.environment.getNextMessageId().toString(),o=`runtime-download-progress-${s}`,a=`runtime-download-error-${s}`,c=`runtime-download-complete-${s}`,d=t=>{const n={downloadedBytes:t.downloadedBytes,totalBytes:t.totalBytes};e(n)},h=()=>{this.removeListener(o,d)};this.on(o,d),this.once(a,t=>{h();const{reason:e,err:i}=t;r(new C({reason:e,error:i},n))}),this.once(c,()=>{h(),i()});const l=Object.assign(t,{downloadId:s});this.wire.sendAction("download-runtime",l).catch(t=>{h(),r(t)})})}downloadPreloadScripts(t){return this.wire.sendAction("download-preload-scripts",{scripts:t}).then(({payload:t})=>t.data)}getAllExternalApplications(){return this.wire.sendAction("get-all-external-applications").then(({payload:t})=>t.data)}getAppAssetInfo(t){return this.wire.sendAction("get-app-asset-info",t).then(({payload:t})=>t.data)}getCookies(t){const e=this.wire.environment.getUrl(),n=Object.assign(t,{url:e});return this.wire.sendAction("get-cookies",n).then(({payload:t})=>t.data)}setMinLogLevel(t){return this.wire.sendAction("set-min-log-level",{level:t}).then(()=>{})}resolveUuid(t){return this.wire.sendAction("resolve-uuid",{entityKey:t}).then(({payload:t})=>t.data)}executeOnRemote(t,e){return e.requestingIdentity=t,this.wire.ferryAction(e)}readRegistryValue(t,e,n){return this.wire.sendAction("read-registry-value",{rootKey:t,subkey:e,value:n}).then(({payload:t})=>t.data)}registerExternalConnection(t){return this.wire.sendAction("register-external-connection",{uuid:t}).then(({payload:t})=>t.data)}async getServiceConfiguration(t){if("string"!=typeof t.name)throw new Error("Must provide an object with a `name` property having a string value");const{name:e}=t;return this.wire.sendAction("get-service-configuration",{name:e}).then(({payload:t})=>t.data)}async getSystemAppConfig(t){if("string"!=typeof t)throw new Error("Must provide a string value for name of system app");return this.wire.sendAction("get-system-app-configuration",{name:t}).then(({payload:t})=>t.data)}async registerShutdownHandler(t){this.wire.recordAnalytic("system-register-shutdown-handler");const{uuid:e,name:n}=this.wire.me;this.on("system-shutdown",i=>{t({proceed:()=>{this.wire.environment.raiseEvent("application/system-shutdown-handled",{uuid:e,name:n,topic:"application"})}})})}runRvmHealthCheck(){return this.wire.sendAction("run-rvm-health-check").then(({payload:t})=>t.data)}async launchManifest(e,n={}){const{subscribe:i,...r}=n,s=r;if(i){const e=new t;i(e);const n="app-version-progress",r="runtime-status",o="app-version-complete",a="app-version-error",c=this.wire.environment.getNextMessageId().toString();s.appVersionId=c;const d=[o,n,r,a],h=t=>{const{appVersionId:e,topic:n,type:i,...r}=t;return{...r,type:d.find(t=>i.includes(t))}},l=t=>{const n=h(t);e.emit(n.type,n)},p=()=>{this.removeListener(`${n}.${c}`,l),this.removeListener(`${r}.${c}`,l),this.removeListener(`${o}.${c}`,l),this.removeListener(`${a}.${c}`,l),this.removeListener(`${o}.${c}`,p),this.removeListener(`${a}.${c}`,p)};await Promise.all([this.on(`${n}.${c}`,l),this.on(`${r}.${c}`,l),this.once(`${o}.${c}`,l),this.once(`${a}.${c}`,l),this.once(`${o}.${c}`,p),this.once(`${a}.${c}`,p)])}return(await this.wire.sendAction("launch-manifest",{manifestUrl:e,opts:s})).payload.data.manifest}async queryPermissionForCurrentContext(t){const e={uuid:this.wire.me.uuid,name:this.wire.me.name};return(await this.wire.sendAction("query-permission-for-current-context",{apiName:t,identity:e})).payload.data}async enableNativeWindowIntegrationProvider(t){const{payload:e}=await this.wire.sendAction("enable-native-window-integration-provider",{permissions:t});return e.data}registerUsage({data:t,type:e}){let n;try{const i=`${e}\0${JSON.stringify(t,D)}`;if(H(this,R,"f").has(i)||H(this,O,"f").has(i))return;H(this,O,"f").add(i),n=i}catch{console.debug(`[registerUsage] Failed to serialize 'data' for deduplication (type: "${e}"). Sending unconditionally.`)}H(this,W,"f").push({payload:{data:t,type:e},dedupKey:n}),H(this,j,"f")||(B(this,j,!0,"f"),queueMicrotask(()=>H(this,G,"m",N).call(this)))}async getPrinters(){const{payload:t}=await this.wire.sendAction("system-get-printers");return t.data}async updateProcessLoggingOptions(t){await this.wire.sendAction("system-update-process-logging-options",{options:t})}async getDomainSettings(){const{payload:{data:t}}=await this.wire.sendAction("get-domain-settings");return t}async setDomainSettings(t){await this.wire.sendAction("set-domain-settings",{domainSettings:t})}async getCurrentDomainSettings(t){return(await this.wire.sendAction("get-current-domain-settings",{identity:t})).payload.data}async resolveDomainSettings(t){return(await this.wire.sendAction("resolve-domain-settings",{url:t})).payload.data}async refreshExtensions(){const{payload:t}=await this.wire.sendAction("refresh-extensions");return t.data}async getInstalledExtensions(){const{payload:t}=await this.wire.sendAction("get-installed-extensions");return t.data}async serveAsset(t){return(await this.wire.sendAction("serve-asset",{options:t})).payload.data}async getThemePreferences(){return(await this.wire.sendAction("get-theme-preferences")).payload.data}async setThemePreferences(t){return(await this.wire.sendAction("set-theme-preferences",{preferences:t})).payload.data}async launchLogUploader(t){return(await this.wire.sendAction("launch-log-uploader",{options:t})).payload.data}async setThemePalette(t){return(await this.wire.sendAction("set-theme-palette",{themePalette:t})).payload.data}async getThemePalette(){const{payload:t}=await this.wire.sendAction("get-theme-palette");return t.data}}R=new WeakMap,O=new WeakMap,W=new WeakMap,j=new WeakMap,G=new WeakSet,N=function(){B(this,j,!1,"f");const t=H(this,W,"f");if(B(this,W,[],"f"),0===t.length)return;const e=t.map(({payload:t})=>t),n=t.map(({dedupKey:t})=>t),i=()=>{for(const t of n)void 0!==t&&H(this,O,"f").delete(t)};(1===e.length?this.wire.sendAction("register-usage",e[0]):this.wire.sendAction("register-usage-batch",{items:e})).then(()=>{for(const t of n)void 0!==t&&(H(this,O,"f").delete(t),H(this,R,"f").add(t))}).catch(t=>{i(),console.debug("[registerUsage] Failed to send usage data.",t)})};class U{constructor(){this.topicRefMap=new Map}incRefCount(t){const e=this.topicRefMap.get(t);let n;if(e){const i=e+1;n=i,this.topicRefMap.set(t,i)}else this.topicRefMap.set(t,1),n=1;return n}decRefCount(t){const e=this.topicRefMap.get(t);let n;if(e){const i=e-1;this.topicRefMap.set(t,i),n=i}else n=-1;return n}actOnFirst(t,e,n){return 1===this.incRefCount(t)?e():n()}actOnLast(t,e,n){return 0===this.decRefCount(t)?e():n()}}const z=t=>async(e,n,i)=>{const r=await t(e,n,i);return void 0===r?n:r};class _{constructor(t,e){this.providerIdentity=t,this.close=e}}class q{static defaultAction(t){throw new Error(`No action registered at target for ${t}`)}constructor(){this.subscriptions=new Map}async processAction(t,e,n){try{const i=this.subscriptions.get(t),r=i??((e,n)=>(this.defaultAction??q.defaultAction)(t,e,n)),s=this.preAction?await this.preAction(t,e,n):e,o=await r(s,n);return this.postAction?await this.postAction(t,o,n):o}catch(e){if(C.trimEndCallSites(e,/Channel.*processAction/),this.errorMiddleware)return this.errorMiddleware(t,e,n);throw e}}beforeAction(t){if(this.preAction)throw new Error("Already registered beforeAction middleware");this.preAction=z(t)}onError(t){if(this.errorMiddleware)throw new Error("Already registered error middleware");this.errorMiddleware=t}afterAction(t){if(this.postAction)throw new Error("Already registered afterAction middleware");this.postAction=z(t)}remove(t){this.subscriptions.delete(t)}setDefaultAction(t){if(this.defaultAction)throw new Error("default action can only be set once");this.defaultAction=t}register(t,e){if(this.subscriptions.has(t))throw new Error(`Subscription already registered for action: ${t}. Unsubscribe before adding new subscription`);return this.subscriptions.set(t,e),!0}}let J=class extends Error{constructor(t,e,n,i){super(t.message),this.action=e,this.dispatchPayload=n,this.name=this.constructor.name,"cause"in t&&t.cause instanceof Error&&(this.cause=t.cause),this.stack=C.prepareStackTrace(this,i)}};var Y,K,Z,Q=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)},X=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n};const tt=new Map;class et extends q{static closeChannelByEndpointId(t){const e=tt.get(t);e&&Q(e,Z,"f").call(e)}static handleProviderDisconnect(t){for(const e of tt.values())e.providerIdentity.channelId===t.channelId&&(e.disconnectListener(t),Q(e,Z,"f").call(e))}constructor(t,e,n){super(),Y.set(this,void 0),K.set(this,void 0),this.processAction=(t,e,n)=>super.processAction(t,e,n),Z.set(this,()=>{tt.delete(this.endpointId),Q(this,K,"f").close()}),X(this,Y,new _(t,e),"f"),this.disconnectListener=()=>{},this.endpointId=t.endpointId,X(this,K,n,"f"),tt.set(this.endpointId,this),n.receive(this.processAction)}get providerIdentity(){return Q(this,Y,"f").providerIdentity}async dispatch(t,e){if(Q(this,K,"f").isEndpointConnected(this.providerIdentity.channelId)){const n=C.getCallSite();return Q(this,K,"f").send(this.providerIdentity.channelId,t,e).catch(i=>{throw new J(i,t,e,n)})}throw new Error("The client you are trying to dispatch from is disconnected from the target provider.")}onDisconnection(t){this.disconnectListener=e=>{try{t(e)}catch(t){throw new Error(`Error while calling the onDisconnection callback: ${t.message}`)}finally{this.disconnectListener=()=>{}}}}async disconnect(){await this.sendDisconnectAction(),Q(this,Z,"f").call(this)}async sendDisconnectAction(){const t=Q(this,Y,"f");await t.close()}static async wireClose(t,e,n){const{channelName:i,uuid:r,name:s}=e;await t.sendAction("disconnect-from-channel",{channelName:i,uuid:r,name:s,endpointId:n})}}function nt(t,e){throw new Error(`Unsupported value: ${t}${e?`\n Supported values are: ${e.join("")}`:""}`)}Y=new WeakMap,K=new WeakMap,Z=new WeakMap;var it,rt,st,ot=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},at=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class ct{constructor(t,e,n,i){this.messageReceiver=e,this.endpointId=n,this.providerIdentity=i,it.set(this,void 0),rt.set(this,new Map),st.set(this,new Map),this.send=async(t,e,n)=>{const i=at(this,rt,"f").get(t);if(!i)throw new Error(`Could not locate routing info for endpoint ${t}`);const r={...i};r.isLocalEndpointId&&delete r.endpointId,delete r.isLocalEndpointId;const s=at(this,it,"f").sendAction("send-channel-message",{...r,providerIdentity:this.providerIdentity,action:e,payload:n});at(this,st,"f").get(t)?.add(s);return(await s.catch(t=>{if("cause"in t)throw t;throw new Error(t.message)}).finally(()=>{at(this,st,"f").get(t)?.delete(s)})).payload.data.result},this.close=async()=>{this.messageReceiver.removeEndpoint(this.providerIdentity.channelId,this.endpointId),[...at(this,rt,"f").keys()].forEach(t=>this.closeEndpoint(t)),ot(this,rt,new Map,"f")},ot(this,it,t,"f")}onEndpointDisconnect(t,e){}receive(t){this.messageReceiver.addEndpoint(t,this.providerIdentity.channelId,this.endpointId)}async closeEndpoint(t){const e=at(this,rt,"f").get(t);at(this,rt,"f").delete(t);const n=at(this,st,"f").get(t);n?.forEach(n=>{const i=`Channel connection with identity uuid: ${e?.uuid} / name: ${e?.name} / endpointId: ${t} no longer connected.`;n.cancel(new Error(i))})}isEndpointConnected(t){return at(this,rt,"f").has(t)}addEndpoint(t,e){at(this,rt,"f").set(t,e.endpointIdentity),at(this,st,"f").set(t,new Set)}isValidEndpointPayload(t){return"string"==typeof t?.endpointIdentity?.endpointId||"string"==typeof t?.endpointIdentity?.channelId}}it=new WeakMap,rt=new WeakMap,st=new WeakMap;const dt={version:5,minimumVersion:0,type:"classic"};function ht(t){const e={stack:t.stack,name:t.name,message:t.message,toString:()=>t.stack||t.toString()};return"cause"in t&&(e.cause=ht(t.cause)),e}var lt,pt,ut=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)},wt=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n};class yt{static isValidEndpointPayload(t){const e=t=>"object"==typeof t&&null!==t;return e(t)&&e(t.endpointIdentity)&&e(t.rtc)&&"string"==typeof t.endpointIdentity.endpointId}constructor({rtc:t,endpointIdentity:e}){this.responseMap=new Map,lt.set(this,null),pt.set(this,void 0),this.connectionStateChangeHandler=t=>{"connected"!==this.rtc.rtcClient.connectionState&&(this.rtc.rtcClient.removeEventListener("connectionstatechange",this.connectionStateChangeHandler),this.close(),ut(this,pt,"f")&&ut(this,pt,"f").call(this))},this.send=async(t,e)=>{const n=`message-${Math.random()}`,i=new Promise((t,e)=>{this.responseMap.set(n,{resolve:t,reject:e})});try{this.rtc.channels.request.send(JSON.stringify({action:t,payload:e,messageId:n}))}catch{this.disconnectOnSendFailure()}return i},this.close=()=>{this.responseMap.forEach(t=>t.reject("Connection has closed.")),this.responseMap=new Map,this.rtc.channels.request.close(),this.rtc.channels.response.close(),this.rtc.rtcClient.close()},this.rtc=t,this.endpointIdentity=e,this.rtc.channels.response.addEventListener("message",t=>{let{data:e}=t;t.data instanceof ArrayBuffer&&(e=(new TextDecoder).decode(t.data));const{messageId:n,payload:i,success:r,error:s}=JSON.parse(e),{resolve:o,reject:a}=this.responseMap.get(n)??{};o&&a?(this.responseMap.delete(n),r?o(i):a(s)):(console.log("Could not find id in responseMap."),console.log(t))}),this.rtc.channels.request.addEventListener("message",async t=>{let{data:n}=t;t.data instanceof ArrayBuffer&&(n=(new TextDecoder).decode(t.data));const{messageId:i,action:r,payload:s}=JSON.parse(n);if(ut(this,lt,"f"))try{const t=await ut(this,lt,"f").call(this,r,s,e);this.sendResponse(JSON.stringify({messageId:i,payload:t,success:!0}))}catch(t){"open"===this.rtc.channels.response.readyState&&this.sendResponse(JSON.stringify({messageId:i,error:ht(t),success:!1}))}else"open"===this.rtc.channels.response.readyState&&this.sendResponse(JSON.stringify({messageId:i,success:!1,error:"Connection not ready."}))}),this.rtc.rtcClient.addEventListener("connectionstatechange",this.connectionStateChangeHandler),Object.values(this.rtc.channels).forEach(t=>{t.onclose=t=>{[...this.responseMap.values()].forEach(t=>t.reject(new Error("RTCDataChannel closed unexpectedly, this is most commonly caused by message size. Note: RTC Channels have a message size limit of ~255kB."))),this.close(),ut(this,pt,"f")&&ut(this,pt,"f").call(this)}})}onDisconnect(t){if(ut(this,pt,"f"))throw new Error("RTCEndpoint disconnectListener cannot be set twice.");wt(this,pt,t,"f")}receive(t){if(ut(this,lt,"f"))throw new Error("You have already set a listener for this RTC Endpoint.");wt(this,lt,t,"f")}sendResponse(t){try{this.rtc.channels.response.send(t)}catch{this.disconnectOnSendFailure()}}disconnectOnSendFailure(){Object.values(this.rtc.channels).forEach(t=>{t.onclose=null}),[...this.responseMap.values()].forEach(t=>t.reject(new Error("RTCDataChannel closed unexpectedly, this is most commonly caused by message size. Note: RTC Channels have a message size limit of ~255kB."))),this.close(),ut(this,pt,"f")&&ut(this,pt,"f").call(this)}get connected(){return"connected"===this.rtc.rtcClient.connectionState}}lt=new WeakMap,pt=new WeakMap;var ft,gt,mt,vt=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)},Ct=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n};class It{constructor(t,e,n){this.EndpointType=t,this.StrategyName=n,ft.set(this,null),gt.set(this,new Map),mt.set(this,!0),this.send=async(t,e,n)=>this.getEndpointById(t).send(e,n),this.close=async()=>{vt(this,mt,"f")&&(vt(this,gt,"f").forEach(t=>t.close()),Ct(this,gt,new Map,"f")),Ct(this,mt,!1,"f")},this.isValidEndpointPayload=e}onEndpointDisconnect(t,e){this.getEndpointById(t).onDisconnect(e)}receive(t){if(vt(this,ft,"f"))throw new Error(`You have already set a listener for this ${this.StrategyName} Strategy`);Ct(this,ft,t,"f"),vt(this,gt,"f").forEach(t=>t.receive(vt(this,ft,"f")))}getEndpointById(t){const e=vt(this,gt,"f").get(t);if(!e)throw new Error(`Client with endpoint id ${t} is not connected`);return e}get connected(){return vt(this,mt,"f")}isEndpointConnected(t){return vt(this,gt,"f").has(t)}addEndpoint(t,e){if(!vt(this,mt,"f"))return void console.warn(`Adding endpoint to disconnected ${this.StrategyName} Strategy`);const n=new this.EndpointType(e);vt(this,ft,"f")&&n.receive(vt(this,ft,"f")),vt(this,gt,"f").set(t,n)}async closeEndpoint(t){vt(this,gt,"f").delete(t)}}ft=new WeakMap,gt=new WeakMap,mt=new WeakMap;class bt extends It{constructor(){super(yt,yt.isValidEndpointPayload,"RTC")}}const xt={version:2,minimumVersion:0,type:"rtc"};class At extends p{constructor(t){super(t,"channel"),this.ensureChannelOpened=t=>new Promise((e,n)=>{if("open"===t.readyState)e();else if("connecting"===t.readyState){const n=()=>{t.removeEventListener("open",n),e()};t.addEventListener("open",n)}else n(new Error("This Channel has already closed"))})}static createDataChannelPromise(t,e){let n;const i=new Promise(t=>{n=t}),r=i=>{const s=()=>{i.channel.removeEventListener("open",s),n(i.channel)};i.channel.label===t&&(i.channel.addEventListener("open",s),e.removeEventListener("datachannel",r))};return e.addEventListener("datachannel",r),i}async listenForProviderIce(t,e){await this.on(this.createProviderEventName(t),e,{timestamp:Date.now()})}async raiseProviderIce(t,e){await this.wire.environment.raiseEvent(this.createRouteString(this.createProviderEventName(t)),e)}async listenForClientIce(t,e){await this.on(this.createClientEventName(t),e,{timestamp:Date.now()})}async raiseClientIce(t,e){await this.wire.environment.raiseEvent(this.createRouteString(this.createClientEventName(t)),e)}cleanupIceListeners(t){this.removeAllListeners(this.createClientEventName(t)),this.removeAllListeners(this.createProviderEventName(t))}createClientEventName(t){return`ice-client-${t}`}createProviderEventName(t){return`ice-provider-${t}`}createRouteString(t){return`channel/${t}`}createRtcPeer(){return this.wire.environment.getRtcPeer()}async startClientOffer(){const t=Math.random().toString(),e=this.createRtcPeer();e.addEventListener("icecandidate",async e=>{e.candidate&&await this.raiseClientIce(t,{candidate:e.candidate?.toJSON()})}),await this.listenForProviderIce(t,async t=>{await e.addIceCandidate(t.candidate)});const n={request:e.createDataChannel("request"),response:e.createDataChannel("response")},i=await e.createOffer();await e.setLocalDescription(i);const r=Promise.all([n.request,n.response].map(this.ensureChannelOpened)).then(()=>{});return{rtcClient:e,channels:n,offer:i,rtcConnectionId:t,channelsOpened:r}}async finishClientOffer(t,e,n){return await t.setRemoteDescription(e),await n,!0}async createProviderAnswer(t,e){const n=this.createRtcPeer(),i=At.createDataChannelPromise("request",n),r=At.createDataChannelPromise("response",n);n.addEventListener("icecandidate",async e=>{e.candidate&&await this.raiseProviderIce(t,{candidate:e.candidate?.toJSON()})}),await this.listenForClientIce(t,async t=>{await n.addIceCandidate(t.candidate)}),await n.setRemoteDescription(e);const s=await n.createAnswer();await n.setLocalDescription(s);const o=Promise.all([i,r]).then(([e,n])=>(this.cleanupIceListeners(t),{request:e,response:n}));return{rtcClient:n,answer:s,channels:o}}}function Et(t){return[...t.split(".").reverse().entries()].reduce((t,[e,n])=>t+ +n*1e4**e,0)}function Pt(t,e){const n=function(t){return t.split("/")[0]}(t);return function(t,e){return Et(t)>=Et(e)}(n,e)}var Mt,St,kt,Tt,Lt,$t,Ft=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)},Gt=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n};class Rt extends q{get connections(){return[...Ft(this,St,"f")]}static handleClientDisconnection(t,e){if(e.endpointId)Ft(t,Lt,"f").call(t,{endpointId:e.endpointId});else{t.connections.filter(t=>t.uuid===e.uuid&&t.name===e.name).forEach(Ft(t,Lt,"f"))}t.disconnectListener(e)}static setProviderRemoval(t,e){Mt.removalMap.set(t,e)}constructor(t,e,n){super(),St.set(this,void 0),kt.set(this,void 0),Tt.set(this,void 0),Lt.set(this,t=>{const e=this.connections.filter(e=>e.endpointId!==t.endpointId);Ft(this,Tt,"f").closeEndpoint(t.endpointId),Gt(this,St,e,"f")}),this.processAction=async(t,e,n)=>(Mt.clientIsMultiRuntime(n)&&!Pt(n.runtimeUuid,"18.87.56.0")?this.handleMultiRuntimeLegacyClient(n):this.checkForClientConnection(n),super.processAction(t,e,n)),$t.set(this,()=>{Ft(this,Tt,"f").close();const t=Mt.removalMap.get(this);t&&t()}),Gt(this,kt,new _(t,e),"f"),this.connectListener=()=>{},this.disconnectListener=()=>{},Gt(this,St,[],"f"),Gt(this,Tt,n,"f"),n.receive(this.processAction)}dispatch(t,e,n){const i=t.endpointId??this.getEndpointIdForOpenFinId(t,e);if(i&&Ft(this,Tt,"f").isEndpointConnected(i)){const t=C.getCallSite();return Ft(this,Tt,"f").send(i,e,n).catch(i=>{throw new J(i,e,n,t)})}return Promise.reject(new Error(`Client connection with identity uuid: ${t.uuid} / name: ${t.name} / endpointId: ${i} no longer connected.`))}async processConnection(t,e){return Ft(this,St,"f").push(t),this.connectListener(t,e)}publish(t,e){return this.connections.map(n=>Ft(this,Tt,"f").send(n.endpointId,t,e))}onConnection(t){this.connectListener=t}onDisconnection(t){this.disconnectListener=e=>{t(e)}}async destroy(){const t=Ft(this,kt,"f");Gt(this,St,[],"f"),await t.close(),Ft(this,$t,"f").call(this)}async getAllClientInfo(){return this.connections.map(t=>{const{uuid:e,name:n,endpointId:i,entityType:r,connectionUrl:s}=t;return{uuid:e,name:n,endpointId:i,entityType:r,connectionUrl:s}})}checkForClientConnection(t){if(!this.isClientConnected(t))throw new Error(`This action was sent from a client that is not connected to the provider.\n Client Identity: {uuid: ${t.uuid}, name: ${t.name}, endpointId: ${t.endpointId}}`)}isClientConnected(t){return Mt.clientIdentityIncludesEndpointId(t)?this.connections.some(e=>e.endpointId===t.endpointId&&e.uuid===t.uuid&&e.name===t.name):this.isLegacyClientConnected(t)}isLegacyClientConnected(t){return this.connections.some(e=>e.uuid===t.uuid&&e.name===t.name)}handleMultiRuntimeLegacyClient(t){if(!this.isLegacyClientConnected(t))throw new Error(`This action was sent from a client that is not connected to the provider. Client Identity:\n {uuid: ${t.uuid}, name: ${t.name}, endpointId: ${t.endpointId}}`)}getEndpointIdForOpenFinId(t,e){const n=this.connections.filter(e=>e.name===t.name&&e.uuid===t.uuid);if(n.length>=2){const n=Ft(this,kt,"f"),{uuid:i,name:r}=t,s=n?.providerIdentity.uuid,o=n?.providerIdentity.name;console.warn(`WARNING: Dispatch call may have unintended results. The "to" argument of your dispatch call is missing the\n "endpointId" parameter. The identity you are dispatching to ({uuid: ${i}, name: ${r}})\n has multiple channelClients for this channel. Your dispatched action: (${e}) from the provider:\n ({uuid: ${s}, name: ${o}}) will only be processed by the most recently-created client.`)}return n.pop()?.endpointId}static clientIdentityIncludesEndpointId(t){return void 0!==t.endpointId}static clientIsMultiRuntime(t){return void 0!==t.runtimeUuid}static async wireClose(t,e){await t.sendAction("destroy-channel",{channelName:e})}}Mt=Rt,St=new WeakMap,kt=new WeakMap,Tt=new WeakMap,Lt=new WeakMap,$t=new WeakMap,Rt.removalMap=new WeakMap;class Ot extends l{constructor(t){super(t),this.onmessage=t=>"process-channel-message"===t.action&&(this.processChannelMessage(t),!0),this.endpointMap=new Map,this.latestEndpointIdByChannelId=new Map,t.registerMessageHandler(this.onmessage.bind(this))}async processChannelMessage(t){const{senderIdentity:e,providerIdentity:n,action:i,ackToSender:r,payload:s,intendedTargetIdentity:o}=t.payload,a=o.channelId??o.endpointId??this.latestEndpointIdByChannelId.get(n.channelId),c=this.endpointMap.get(a);if(!c)return r.payload.success=!1,r.payload.reason=`Client connection with identity uuid: ${this.wire.me.uuid} / name: ${this.wire.me.name} / endpointId: ${a} no longer connected.`,r.payload.error=ht(new Error(r.payload.reason)),this.wire.sendRaw(r);try{const t=await c(i,s,e);return r.payload.payload=r.payload.payload||{},r.payload.payload.result=t,this.wire.sendRaw(r)}catch(t){return r.payload.success=!1,r.payload.reason=t.message,r.payload.error=ht(t),this.wire.sendRaw(r)}}addEndpoint(t,e,n){this.endpointMap.set(n,t),e!==n&&this.latestEndpointIdByChannelId.set(e,n)}removeEndpoint(t,e){this.endpointMap.delete(e),this.latestEndpointIdByChannelId.get(t)===e&&this.latestEndpointIdByChannelId.delete(t)}checkForPreviousClientConnection(t){const e=this.latestEndpointIdByChannelId.get(t);e&&(et.closeChannelByEndpointId(e),console.warn("You have created a second connection to an older provider. First connection has been removed from the clientMap"),console.warn("If the provider calls publish(), you may receive multiple messages."))}}class Wt{constructor(t){this.ProtocolsInPreferenceOrder=t,this.DefaultClientProtocols=["classic"],this.DefaultProviderProtocols=["classic"],this.getClientProtocols=t=>{const e=t?this.ProtocolsInPreferenceOrder.filter(e=>t.includes(e)):this.DefaultClientProtocols;if(!e.length)throw new Error(`No valid protocols were passed in. Accepted values are: ${this.ProtocolsInPreferenceOrder.join(", ")}.`);return e},this.getProviderProtocols=t=>{const e=t?this.ProtocolsInPreferenceOrder.filter(e=>t.includes(e)):this.DefaultProviderProtocols;if(!e.length)throw new Error(`No valid protocols were passed in. Accepted values are: ${this.ProtocolsInPreferenceOrder.join(", ")}.`);return e},this.getCompatibleProtocols=(t,e)=>e.supportedProtocols.filter(e=>t.some(t=>t.type===e.type&&e.version>=t.minimumVersion&&t.version>=(e.minimumVersion??0))).slice(0,e.maxProtocols)}}class jt{static combine(t,e){return new jt(t,e)}constructor(t,e){this.primary=t,this.secondary=e}onEndpointDisconnect(t,e){this.primary.onEndpointDisconnect(t,()=>{this.secondary.isEndpointConnected(t)||e()}),this.secondary.onEndpointDisconnect(t,()=>{this.primary.isEndpointConnected(t)||e()})}isValidEndpointPayload(t){return this.primary.isValidEndpointPayload(t)||this.secondary.isValidEndpointPayload(t)}async closeEndpoint(t){await this.primary.closeEndpoint(t),await this.secondary.closeEndpoint(t)}isEndpointConnected(t){return this.primary.isEndpointConnected(t)||this.secondary.isEndpointConnected(t)}async addEndpoint(t,e){this.primary.isValidEndpointPayload(e)&&await this.primary.addEndpoint(t,e),this.secondary.isValidEndpointPayload(e)&&await this.secondary.addEndpoint(t,e)}receive(t){this.primary.receive(t),this.secondary.receive(t)}send(t,e,n){return this.primary.isEndpointConnected(t)?this.primary.send(t,e,n):this.secondary.send(t,e,n)}async close(){await Promise.all([this.primary.close(),this.secondary.close()])}}var Nt,Ht,Bt=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},Dt=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class Vt extends l{static getProtocolOptionsFromStrings(t){return t.map(t=>{switch(t){case"rtc":return xt;case"classic":return dt;default:return nt(t,["rtc","classic"])}})}constructor(t){super(t),Nt.set(this,void 0),Ht.set(this,void 0),this.removeChannelFromProviderMap=t=>{const e=this.providerMap.get(t);if(e){const{channelName:n}=e.providerIdentity;this.providerChannelIdByName.get(n)===t&&this.providerChannelIdByName.delete(n)}this.providerMap.delete(t)},this.onmessage=t=>"process-channel-connection"===t.action&&(this.processChannelConnection(t),!0),this.providerMap=new Map,this.providerChannelIdByName=new Map,this.protocolManager=new Wt("node"===this.wire.environment.type?["classic"]:["rtc","classic"]),Bt(this,Nt,new Ot(t),"f"),Bt(this,Ht,new At(t),"f"),t.registerMessageHandler(this.onmessage.bind(this))}createProvider(t,e){const n=Object.assign(this.wire.environment.getDefaultChannelOptions().create,t||{}),i=this.protocolManager.getProviderProtocols(n?.protocols),r=i.map(t=>{switch(t){case"rtc":return new bt;case"classic":return new ct(this.wire,Dt(this,Nt,"f"),e.channelId,e);default:return nt(t,["rtc","classic"])}});let s;if(2===r.length){const[t,e]=r;s=jt.combine(t,e)}else{if(1!==r.length)throw new Error("failed to combine strategies");[s]=r}const o=new Rt(e,()=>Rt.wireClose(this.wire,e.channelName),s),a=e.channelId;return this.providerMap.set(a,{providerIdentity:e,provider:o,strategy:s,supportedProtocols:Vt.getProtocolOptionsFromStrings(i)}),this.providerChannelIdByName.set(e.channelName,a),Rt.setProviderRemoval(o,this.removeChannelFromProviderMap.bind(this)),o}async createClientOffer(t){const e=this.protocolManager.getClientProtocols(t?.protocols);let n;return{offer:{supportedProtocols:await Promise.all(e.map(async t=>{switch(t){case"rtc":{const{rtcClient:t,channels:e,offer:i,rtcConnectionId:r,channelsOpened:s}=await Dt(this,Ht,"f").startClientOffer();return n={rtcClient:t,channels:e,channelsOpened:s},{type:"rtc",version:xt.version,payload:{offer:i,rtcConnectionId:r}}}case"classic":return{type:"classic",version:dt.version};default:return nt(t,["rtc","classic"])}})),maxProtocols:2},rtc:n}}async createClientStrategy(t,e){e.endpointId||(e.endpointId=this.wire.environment.getNextMessageId(),Dt(this,Nt,"f").checkForPreviousClientConnection(e.channelId));const n=e.answer??{supportedProtocols:[{type:"classic",version:1}]},i=(await Promise.all(n.supportedProtocols.map(async n=>"rtc"===n.type&&t?(await Dt(this,Ht,"f").finishClientOffer(t.rtcClient,n.payload.answer,t.channelsOpened),new bt):"classic"===n.type?new ct(this.wire,Dt(this,Nt,"f"),e.endpointId,e):null))).filter(t=>null!==t);let r;if(t&&!i.some(t=>t instanceof bt)&&t&&t.rtcClient.close(),i.length>=2)r=jt.combine(i[0],i[1]);else{if(!i.length)throw new Error("No compatible protocols");[r]=i}const s={endpointIdentity:e,rtc:t};return r.addEndpoint(e.channelId,s),r}handleClientDisconnection(t){const e=t.channelId??this.providerChannelIdByName.get(t.channelName??"");if(!e)return;const n=this.providerMap.get(e);n&&Rt.handleClientDisconnection(n.provider,t)}async processChannelConnection(t){const{clientIdentity:e,providerIdentity:n,ackToSender:i,payload:r,offer:s}=t.payload;e.endpointId?e.isLocalEndpointId=!1:(e.endpointId=this.wire.environment.getNextMessageId(),e.isLocalEndpointId=!0);const o=n.channelId,a=this.providerMap.get(o);if(!a)return i.payload.success=!1,i.payload.reason=`Channel "${n.channelName}" has been destroyed.`,this.wire.sendRaw(i);const{provider:c,strategy:d,supportedProtocols:h}=a;try{if(!(c instanceof Rt))throw Error("Cannot connect to a channel client");const t=s??{supportedProtocols:[{type:"classic",version:1}],maxProtocols:1},n=this.protocolManager.getCompatibleProtocols(h,t);if(!n.length)throw new Error("This provider does not support any of the offered protocols.");const o=await c.processConnection(e,r);i.payload.payload=i.payload.payload||{};let a={supportedProtocols:[],endpointPayloadPromise:Promise.resolve({endpointIdentity:e})};return a=await n.reduce(async(t,e)=>{const n=await t;if("rtc"===e.type){const{answer:t,rtcClient:i,channels:r}=await Dt(this,Ht,"f").createProviderAnswer(e.payload.rtcConnectionId,e.payload.offer);n.supportedProtocols.push({type:"rtc",version:xt.version,payload:{answer:t}}),n.endpointPayloadPromise=n.endpointPayloadPromise.then(t=>r.then(e=>({...t,rtc:{rtcClient:i,channels:e}})))}else n.supportedProtocols.push({type:"classic",version:dt.version});return n},Promise.resolve(a)),a.endpointPayloadPromise.then(t=>d.addEndpoint(e.endpointId,t)),i.payload.payload.result=o,i.payload.payload.answer=a,this.wire.sendRaw(i)}catch(t){return i.payload.success=!1,i.payload.reason=t.message,this.wire.sendRaw(i)}}}Nt=new WeakMap,Ht=new WeakMap;var Ut,zt,_t,qt,Jt=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},Yt=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};function Kt(t){const e=Math.floor(t/10),n=Math.min(3e4,500*2**e);return new Promise(t=>{setTimeout(()=>{t(!1)},n)})}class Zt extends p{constructor(e){super(e,"channel"),Ut.set(this,void 0),zt.set(this,new t),_t.set(this,new E(async()=>{await this.on("client-disconnected",t=>{Yt(this,Ut,"f").handleClientDisconnection(t)})})),qt.set(this,new E(async()=>{await Promise.all([Yt(this,_t,"f").getValue(),this.on("disconnected",t=>{et.handleProviderDisconnect(t)}),this.on("connected",(...t)=>{Yt(this,zt,"f").emit("connected",...t)})]).catch(()=>new Error("error setting up channel connection listeners"))})),Jt(this,Ut,new Vt(e),"f")}async getAllChannels(){return this.wire.sendAction("get-all-channels").then(({payload:t})=>t.data)}async onChannelConnect(t){await this.on("connected",t)}async onChannelDisconnect(t){await this.on("disconnected",t)}async safeConnect(t,e,n){const i={count:0};do{let r=()=>{};const s=new Promise(e=>{r=n=>{t===n.channelName&&e(!0)},Yt(this,zt,"f").on("connected",r)});try{if(i.count>0){i.gotConnectedEvent=await Promise.race([Kt(i.count),s]);const e=await this.wire.sendAction("connect-to-channel",{...n,retryInfo:i});return console.log(`Successfully connected to channelName: ${t}`),e.payload.data}const e=this.wire.sendAction("connect-to-channel",n);i.originalMessageId=e.messageId;return(await e).payload.data}catch(n){if(!n.message.includes("internal-nack"))throw n;e&&0===i.count&&console.warn(`No channel found for channelName: ${t}. Waiting for connection...`)}finally{i.count+=1,Yt(this,zt,"f").removeListener("connected",r)}}while(e);throw new Error(`No channel found for channelName: ${t}.`)}async connect(t,e={}){if(await Yt(this,qt,"f").getValue(),!t||"string"!=typeof t)throw new Error("Please provide a channelName string to connect to a channel.");const n={wait:!0,...this.wire.environment.getDefaultChannelOptions().connect,...e},{offer:i,rtc:r}=await Yt(this,Ut,"f").createClientOffer(n);let s;(this.fin.me.isFrame||this.fin.me.isView||this.fin.me.isWindow)&&(s=(await this.fin.me.getInfo()).url);const o={channelName:t,...n,offer:i,connectionUrl:s},a=await this.safeConnect(t,n.wait,o),c=await Yt(this,Ut,"f").createClientStrategy(r,a),d=new et(a,()=>et.wireClose(this.wire,a,a.endpointId),c);return c.onEndpointDisconnect(a.channelId,async()=>{try{await d.sendDisconnectAction()}catch(t){console.warn(`Something went wrong during disconnect for client with uuid: ${a.uuid} / name: ${a.name} / endpointId: ${a.endpointId}.`)}finally{et.handleProviderDisconnect(a)}}),d}async create(t,e){if(await Yt(this,_t,"f").getValue(),!t)throw new Error("Please provide a channelName to create a channel");const{payload:{data:n}}=await this.wire.sendAction("create-channel",{channelName:t});return Yt(this,Ut,"f").createProvider(e,n)}}Ut=new WeakMap,zt=new WeakMap,_t=new WeakMap,qt=new WeakMap;class Qt extends l{constructor(e){super(e),this.events={subscriberAdded:"subscriber-added",subscriberRemoved:"subscriber-removed"},this.refCounter=new U,this.Channel=new Zt(e),this.emitter=new t,e.registerMessageHandler(this.onmessage.bind(this)),this.on=this.emitter.on.bind(this.emitter),this.removeAllListeners=this.emitter.removeAllListeners.bind(this.emitter)}async publish(t,e){await this.wire.sendAction("publish-message",{topic:t,message:e,sourceWindowName:this.me.name})}async send(t,e,n){const i=I(t);if(i)throw new Error(i);await this.wire.sendAction("send-message",{destinationUuid:t.uuid,destinationWindowName:t.name,topic:e,message:n,sourceWindowName:this.me.name})}subscribe(t,e,n){const i=this.createSubscriptionKey(t.uuid,t.name||"*",e);return this.emitter.on(i,n),this.refCounter.actOnFirst(i,async()=>{await this.wire.sendAction("subscribe",{sourceUuid:t.uuid,sourceWindowName:t.name||"*",topic:e,destinationWindowName:this.me.name})},()=>Promise.resolve())}unsubscribe(t,e,n){const i=t.name||"*",r=this.createSubscriptionKey(t.uuid,i,e);return this.emitter.removeListener(r,n),this.refCounter.actOnLast(r,async()=>{await this.wire.sendAction("unsubscribe",{sourceUuid:t.uuid,sourceWindowName:i,topic:e,destinationWindowName:this.me.name})},()=>new Promise(t=>t).then(()=>{}))}processMessage(t){const{payload:{message:e,sourceWindowName:n,sourceUuid:i,topic:r}}=t,s=[this.createSubscriptionKey(i,n,r),this.createSubscriptionKey(i,"*",r),this.createSubscriptionKey("*","*",r)],o={uuid:i,name:n};s.forEach(t=>{this.emitter.emit(t,e,o)})}emitSubscriverEvent(t,e){const{payload:{targetName:n,uuid:i,topic:r}}=e,s={name:n,uuid:i,topic:r};this.emitter.emit(t,s)}createSubscriptionKey(t,e,n){const i=e||"*";if(!(t&&i&&n))throw new Error("Missing uuid, name, or topic string");return function(...t){return t.map(t=>btoa(t)).join("/")}(t,i,n)}onmessage(t){const{action:e}=t;switch(e){case"process-message":this.processMessage(t);break;case this.events.subscriberAdded:this.emitSubscriverEvent(this.events.subscriberAdded,t);break;case this.events.subscriberRemoved:this.emitSubscriverEvent(this.events.subscriberRemoved,t)}return!0}}class Xt extends l{async writeText(t){await this.wire.sendAction("clipboard-write-text",t)}async readText(t){const{payload:e}=await this.wire.sendAction("clipboard-read-text",{type:t});return e.data}async writeImage(t){await this.wire.sendAction("clipboard-write-image",t)}async readImage(t={format:"dataURL"}){const{payload:e}=await this.wire.sendAction("clipboard-read-image",t);return e.data}async writeHtml(t){await this.wire.sendAction("clipboard-write-html",t)}async readHtml(t){const{payload:e}=await this.wire.sendAction("clipboard-read-html",{type:t});return e.data}async writeRtf(t){await this.wire.sendAction("clipboard-write-rtf",t)}async readRtf(t){const{payload:e}=await this.wire.sendAction("clipboard-read-rtf",{type:t});return e.data}async write(t){await this.wire.sendAction("clipboard-write",t)}async getAvailableFormats(t){const{payload:e}=await this.wire.sendAction("clipboard-read-formats",{type:t});return e.data}}class te extends p{constructor(t,e){super(t,"external-application",e.uuid),this.identity=e}getInfo(){return this.wire.sendAction("get-external-application-info",this.identity).then(({payload:t})=>t.data)}}class ee extends l{wrap(t){return this.wire.recordAnalytic("external-application-wrap"),Promise.resolve(new te(this.wire,{uuid:t}))}wrapSync(t){return this.wire.recordAnalytic("external-application-wrap-sync"),new te(this.wire,{uuid:t})}}class ne extends p{constructor(t,e){super(t,"frame",e.uuid,e.name),this.identity=e}getInfo(){return this.wire.sendAction("get-frame-info",this.identity).then(({payload:t})=>t.data)}getParentWindow(){return this.wire.sendAction("get-parent-window",this.identity).then(({payload:t})=>t.data)}}class ie extends l{async wrap(t){this.wire.recordAnalytic("frame-wrap");const e=I(t);if(e)throw new Error(e);return new ne(this.wire,t)}wrapSync(t){this.wire.recordAnalytic("frame-wrap-sync");const e=I(t);if(e)throw new Error(e);return new ne(this.wire,t)}getCurrent(){return this.wire.recordAnalytic("frame-get-current"),Promise.resolve(new ne(this.wire,this.wire.environment.getCurrentEntityIdentity()))}getCurrentSync(){return this.wire.recordAnalytic("frame-get-current-sync"),new ne(this.wire,this.wire.environment.getCurrentEntityIdentity())}}class re extends p{constructor(t){super(t,"global-hotkey")}async register(t,e){await this.on(t,e),await this.wire.sendAction("global-hotkey-register",{hotkey:t})}async unregister(t){await this.removeAllListeners(t),await this.wire.sendAction("global-hotkey-unregister",{hotkey:t})}async unregisterAll(){await Promise.all(this.eventNames().filter(t=>!("registered"===t||"unregistered"===t)).map(t=>this.removeAllListeners(t))),await this.wire.sendAction("global-hotkey-unregister-all",{})}async isRegistered(t){const{payload:{data:e}}=await this.wire.sendAction("global-hotkey-is-registered",{hotkey:t});return e}}var se,oe,ae,ce=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},de=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class he extends p{constructor(t,e,n=`custom-frame-${e.uuid}`){super(t,"application",e.uuid),oe.set(this,void 0),this.getClient=(t=this.identity)=>{if(t.uuid!==this.identity.uuid)return new se(this.wire,t).getClient();if(this.wire.sendAction("platform-get-client",this.identity).catch(t=>{}),!se.clientMap.has(de(this,oe,"f"))){const t=de(this,ae,"f").call(this);se.clientMap.set(de(this,oe,"f"),t)}return se.clientMap.get(de(this,oe,"f"))},ae.set(this,async()=>{try{const t=await this._channel.connect(de(this,oe,"f"),{wait:!1});return t.onDisconnection(()=>{se.clientMap.delete(de(this,oe,"f"))}),t}catch(t){throw se.clientMap.delete(de(this,oe,"f")),new Error("The targeted Platform is not currently running. Listen for application-started event for the given Uuid.")}}),this.launchLegacyManifest=this.launchContentManifest;const i=I(e);if(i)throw new Error(i);ce(this,oe,n,"f"),this._channel=this.fin.InterApplicationBus.Channel,this.identity={uuid:e.uuid},this.Layout=this.fin.Platform.Layout,this.Application=this.fin.Application.wrapSync(this.identity)}async createView(t,e,n){this.wire.sendAction("platform-create-view",this.identity).catch(t=>{});const i=await this.getClient(),r=await i.dispatch("create-view",{target:e,opts:t,targetView:n});if(!r||I(r.identity))throw new Error(`When overwriting the createView call, please return an object that has a valid 'identity' property: ${JSON.stringify(r)}`);return this.fin.View.wrapSync(r.identity)}async createWindow(t){this.wire.sendAction("platform-create-window",this.identity).catch(t=>{});const e=await this.getClient();t.reason||(t.reason="api-call");const n=await e.dispatch("create-view-container",t);if(!n||I(n.identity))throw new Error(`When overwriting the createWindow call, please return an object that has a valid 'identity' property: ${JSON.stringify(n)}`);const{identity:i}=n,r=this.fin.Window.wrapSync(i);return r.name=i.name,r.uuid=i.uuid,r}async quit(){this.wire.sendAction("platform-quit",this.identity).catch(t=>{});return(await this.getClient()).dispatch("quit")}async closeView(t){this.wire.sendAction("platform-close-view",this.identity).catch(t=>{});const e=await this.getClient();await e.dispatch("close-view",{view:t})}async reparentView(t,e){console.warn("Platform.reparentView has been deprecated, please use Platform.createView"),this.wire.sendAction("platform-reparent-view",this.identity).catch(t=>{});const n={...t,uuid:t.uuid??this.identity.uuid},i=await this.fin.View.wrap(n),r=await i.getOptions();return this.createView(r,e)}async getSnapshot(){this.wire.sendAction("platform-get-snapshot",this.identity).catch(t=>{});return(await this.getClient()).dispatch("get-snapshot")}async getViewSnapshot(t){return(await this.getClient()).dispatch("get-view-snapshot",{viewIdentity:t})}async applySnapshot(t,e){this.wire.sendAction("platform-apply-snapshot",this.identity).catch(t=>{});const n="Requested snapshot must be a valid Snapshot object, or a url or filepath to such an object.";let i;if("string"==typeof t)try{i=(await this._channel.wire.sendAction("get-application-manifest",{manifestUrl:t})).payload.data}catch(t){throw new Error(`${n}: ${t}`)}else i=t;if(!i.windows)throw new Error(n);const r=await this.getClient();return await r.dispatch("apply-snapshot",{snapshot:i,options:e}),this}async fetchManifest(t){return(await this.getClient()).dispatch("platform-fetch-manifest",{manifestUrl:t})}async launchContentManifest(t){this.wire.sendAction("platform-launch-content-manifest",this.identity).catch(()=>{});const e=await this.getClient(),n=await this.fetchManifest(t);return e.dispatch("launch-into-platform",{manifest:n,manifestUrl:t}),this}async setWindowContext(t={},e){if(this.wire.sendAction("platform-set-window-context",this.identity).catch(t=>{}),!t)throw new Error("Please provide a serializable object or string to set the context.");const n=await this.getClient(),{entityType:i}=e?await this.fin.System.getEntityInfo(e.uuid,e.name):this.fin.me;await n.dispatch("set-window-context",{context:t,entityType:i,target:e||{uuid:this.fin.me.uuid,name:this.fin.me.name}})}async getWindowContext(t){this.wire.sendAction("platform-get-window-context",this.identity).catch(t=>{});const e=await this.getClient(),{entityType:n}=t?await this.fin.System.getEntityInfo(t.uuid,t.name):this.fin.me;return e.dispatch("get-window-context",{target:t||{uuid:this.fin.me.uuid,name:this.fin.me.name},entityType:n})}async closeWindow(t,e={skipBeforeUnload:!1}){this.wire.sendAction("platform-close-window",this.identity).catch(t=>{});return(await this.getClient()).dispatch("close-window",{windowId:t,options:e})}}se=he,oe=new WeakMap,ae=new WeakMap,he.clientMap=new Map;class le{constructor(t){this.strategy=t,this.consume=async t=>(await this.strategy.getExposedFunctions(t)).reduce((e,n)=>({...e,[n.key]:this.strategy.createFunction(n,t)}),{})}}class pe{constructor(t){this.channel=t,this.getExposedFunctions=async t=>{const{id:e}=t,{props:n}=await this.channel.dispatch(`api-meta:${e}`);return n},this.createFunction=t=>(...e)=>{const{action:n}=t.options;return this.channel.dispatch(n,{args:e})}}}const ue=["no longer connected","RTCDataChannel closed unexpectedly","The client you are trying to dispatch from is disconnected from the target provider"],we=async(t,e)=>{t.register(`relay:${e}`,({action:e,target:n,payload:i})=>t.dispatch(n,e,i)),await Promise.resolve()},ye=(t,e,n,i)=>async(r,s)=>{try{return await t.dispatch(`relay:${n}`,{action:r,payload:s,target:e})}catch(t){if(o=t.message,ue.some(t=>o.includes(t))&&i)throw new Error(i);throw t}var o};var fe,ge,me,ve,Ce=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},Ie=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class be{constructor(t,e){ge.set(this,void 0),this.isRoot=()=>Ie(this,ge,"f").isRoot(this.entityId),this.exists=()=>Ie(this,ge,"f").exists(this.entityId),this.getParent=async()=>{const t=await Ie(this,ge,"f").getParent(this.entityId);if(t)return fe.getEntity(t,Ie(this,ge,"f"))},this.createAdjacentStack=async(t,e)=>{const n=await Ie(this,ge,"f").createAdjacentStack(this.entityId,t,e);return fe.getEntity({entityId:n,type:"stack"},Ie(this,ge,"f"))},this.getAdjacentStacks=async t=>(await Ie(this,ge,"f").getAdjacentStacks({targetId:this.entityId,edge:t})).map(t=>fe.getEntity({type:"stack",entityId:t.entityId},Ie(this,ge,"f"))),Ce(this,ge,t,"f"),this.entityId=e}}fe=be,ge=new WeakMap,be.newLayoutEntitiesClient=async(t,e,n)=>{const i=ye(t,n,"layout-relay","You are trying to interact with a layout component on a window that does not exist or has been destroyed.");return new le(new pe({dispatch:i})).consume({id:e})},be.getEntity=(t,e)=>{const{entityId:n,type:i}=t;switch(i){case"column":case"row":return new Ae(e,n,i);case"stack":return new xe(e,n);default:throw new Error(`Unrecognised Layout Entity encountered ('${JSON.stringify(t)})`)}};class xe extends be{constructor(t,e){super(t,e),me.set(this,void 0),this.type="stack",this.getViews=()=>Ie(this,me,"f").getStackViews(this.entityId),this.addView=async(t,e={index:0})=>Ie(this,me,"f").addViewToStack(this.entityId,t,e),this.removeView=async t=>{await Ie(this,me,"f").removeViewFromStack(this.entityId,t)},this.setActiveView=async t=>{await Ie(this,me,"f").setStackActiveView(this.entityId,t)},Ce(this,me,t,"f")}}me=new WeakMap;class Ae extends be{constructor(t,e,n){super(t,e),ve.set(this,void 0),this.getContent=async()=>(await Ie(this,ve,"f").getContent(this.entityId)).map(t=>be.getEntity(t,Ie(this,ve,"f"))),Ce(this,ve,t,"f"),this.type=n}}ve=new WeakMap;const Ee="layout-entities";var Pe,Me,Se,ke=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class Te extends l{static getClient(t){return ke(t,Me,"f").getValue()}constructor(t,e){super(e),Pe.add(this),Me.set(this,new A(async()=>be.newLayoutEntitiesClient(await this.platform.getClient(),Ee,this.identity))),this.replace=async t=>{this.wire.sendAction("layout-replace").catch(t=>{});const e=await this.platform.getClient();await e.dispatch("replace-layout",{target:this.identity,opts:{layout:t}})},this.replaceView=async(t,e)=>{this.wire.sendAction("layout-replace-view").catch(t=>{});const n=await this.platform.getClient();await n.dispatch("replace-view",{target:this.identity,opts:{viewToReplace:t,newView:e}})},this.applyPreset=async t=>{this.wire.sendAction("layout-apply-preset").catch(t=>{});const e=await this.platform.getClient(),{presetType:n}=t;if(!n||!function(t){switch(t){case"columns":case"grid":case"rows":case"tabs":return!0;default:return!1}}(n))throw new Error("Cannot apply preset layout, please include an applicable presetType property in the PresetLayoutOptions.");await e.dispatch("apply-preset-layout",{target:this.identity,opts:{presetType:n}})};const n=I(t);if(n)throw new Error(n);this.identity=t,this.platform=this.fin.Platform.wrapSync({uuid:t.uuid}),t.uuid===this.fin.me.uuid&&t.name===this.fin.me.name&&(this.init=this.fin.Platform.Layout.init)}async getConfig(){this.wire.sendAction("layout-get-config").catch(t=>{});return(await this.platform.getClient()).dispatch("get-frame-snapshot",{target:this.identity})}async getCurrentViews(){this.wire.sendAction("layout-get-views").catch(t=>{});const t=await this.platform.getClient();return(await t.dispatch("get-layout-views",{target:this.identity})).map(t=>this.fin.View.wrapSync(t))}async getRootItem(){this.wire.sendAction("layout-get-root-item").catch(()=>{});const t=await ke(this,Me,"f").getValue(),e=await t.getRoot("layoutName"in this.identity?this.identity:void 0);return be.getEntity(e,t)}async getStackByViewIdentity(t){this.wire.sendAction("layout-get-stack-by-view").catch(()=>{});const e=await ke(this,Me,"f").getValue(),n=await e.getStackByView(t);if(!n)throw new Error(`No stack found for view: ${t.uuid}/${t.name}`);return be.getEntity(n,e)}async addView(t,{location:e,targetView:n}={}){this.wire.sendAction("layout-add-view").catch(t=>{});const{identity:i}=await ke(this,Pe,"m",Se).call(this,"layout-add-view",{viewOptions:t,location:e,targetView:n});return{identity:i}}async closeView(t){this.wire.sendAction("layout-close-view").catch(t=>{}),await ke(this,Pe,"m",Se).call(this,"layout-close-view",{viewIdentity:t})}}Me=new WeakMap,Pe=new WeakSet,Se=async function(t,e){return(await this.platform.getClient()).dispatch(t,{target:this.identity,opts:e})};var Le,$e,Fe,Ge,Re,Oe=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)},We=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n};class je extends l{constructor(){super(...arguments),Le.add(this),$e.set(this,!1),Fe.set(this,null),this.init=async(t={})=>{if(this.wire.recordAnalytic("layout-init"),!this.wire.environment.layoutAllowedInContext(this.fin))throw new Error("Layout.init can only be called from a Window context.");if(Oe(this,$e,"f"))throw new Error("Layout.init was already called, please use Layout.create to add additional layouts.");"openfin"===this.wire.environment.type&&await this.fin.Platform.getCurrentSync().getClient(),We(this,$e,!0,"f"),We(this,Fe,await this.wire.environment.initLayoutManager(this.fin,this.wire,t),"f"),await this.wire.environment.applyLayoutSnapshot(this.fin,Oe(this,Fe,"f"),t);const e={name:this.fin.me.name,uuid:this.fin.me.uuid};if(!t.layoutManagerOverride){const t={layoutName:"__default__",...e};return Oe(this,Ge,"f").call(this,t)}return this.wrapSync(e)},Ge.set(this,t=>{const e="[Layout] You are using a deprecated property `layoutManager` - it will throw if you access it starting in v37.",n=new Proxy({},{get(t,n){throw console.warn(`[Layout-mgr-proxy] accessing ${n.toString()}`),new Error(e)}}),i=Object.assign(this.wrapSync(t),{layoutManager:n});return new Proxy(i,{get(t,n){if("layoutManager"===n)throw console.warn(`[Layout-proxy] accessing ${n.toString()}`),new Error(e);return t[n]}})}),this.getCurrentLayoutManagerSync=()=>Oe(this,Le,"m",Re).call(this,"fin.Platform.Layout.getCurrentLayoutManagerSync()"),this.create=async t=>this.wire.environment.createLayout(Oe(this,Le,"m",Re).call(this,"fin.Platform.Layout.create()"),t),this.destroy=async t=>this.wire.environment.destroyLayout(Oe(this,Le,"m",Re).call(this,"fin.Platform.Layout.destroy()"),t)}async wrap(t){return this.wire.recordAnalytic("layout-wrap"),new Te(t,this.wire)}wrapSync(t){return this.wire.recordAnalytic("layout-wrap-sync"),new Te(t,this.wire)}async getCurrent(){if(this.wire.recordAnalytic("layout-get-current"),"openfin"===this.wire.environment.type&&!this.fin.me.isWindow)throw new Error("You are not in a Window context. Only Windows can have a Layout.");const{uuid:t,name:e}=this.fin.me;return this.wrap({uuid:t,name:e})}getCurrentSync(){if(this.wire.recordAnalytic("layout-get-current-sync"),"openfin"===this.wire.environment.type&&!this.fin.me.isWindow)throw new Error("You are not in a Window context. Only Windows can have a Layout.");const{uuid:t,name:e}=this.fin.me;return this.wrapSync({uuid:t,name:e})}async getLayoutByViewIdentity(t){this.wire.recordAnalytic("layout-get-by-view-identity");let e=await this.wire.environment.getViewWindowIdentity(this.fin,t);e.identity&&(e=e.identity);try{const n=this.wrapSync(e),i=await Te.getClient(n),r=await i.getLayoutIdentityForViewOrThrow(t);return this.wrapSync(r)}catch(n){if(!["No action registered at target for","getLayoutIdentityForViewOrThrow is not a function"].some(t=>n.message.includes(t)))throw n;if(e.uuid===e.name)throw new Error(`View identity ${JSON.stringify(t)} is not attached to any layout in provider window ${JSON.stringify(e)}.`);return this.wrapSync(e)}}}$e=new WeakMap,Fe=new WeakMap,Ge=new WeakMap,Le=new WeakSet,Re=function(t){if(!Oe(this,Fe,"f"))throw new Error(`You must call init before using the API ${t}`);return Oe(this,Fe,"f")};class Ne extends l{constructor(t,e){super(t),this._channel=e,this.Layout=new je(this.wire)}async init(t){if(!fin.__internal_.isPlatform||fin.me.name!==fin.me.uuid)throw new Error("fin.Platform.init should only be called from a custom platform provider running in the main window of the application.");return this.wire.environment.initPlatform(this.fin,t)}async wrap(t){return this.wire.recordAnalytic("platform-wrap"),new he(this.wire,{uuid:t.uuid})}wrapSync(t){return this.wire.recordAnalytic("platform-wrap-sync"),new he(this.wire,{uuid:t.uuid})}async getCurrent(){return this.wire.recordAnalytic("platform-get-current"),this.wrap({uuid:this.wire.me.uuid})}getCurrentSync(){return this.wire.recordAnalytic("platform-get-current-sync"),this.wrapSync({uuid:this.wire.me.uuid})}start(t){return this.wire.recordAnalytic("platform-start"),new Promise(async(e,n)=>{try{const{uuid:n}=t,i=await this.fin.Application._create({...t,isPlatformController:!0});i.once("platform-api-ready",()=>e(this.wrapSync({uuid:n}))),i._run({uuid:n})}catch(t){n(t)}})}startFromManifest(t,e){return this.wire.recordAnalytic("platform-start-from-manifest"),new Promise(async(n,i)=>{try{const i=await this.fin.Application._createFromManifest(t);i.once("platform-api-ready",()=>n(this.wrapSync({uuid:i.identity.uuid}))),i._run(e)}catch(t){i(t)}})}}const He="You are not running in OpenFin.";function Be(t,e,n){return{...{isView:"view"===t,isWindow:"window"===t,isFrame:"iframe"===t,isExternal:"external connection"===t},uuid:e,name:n,entityType:t}}const De=()=>`${Math.random()}${Date.now()}`,Ve=(t,e)=>(...n)=>{try{return t(...n)}catch(t){throw new Error((e||"")+t)}},Ue=(t,e)=>async n=>{try{await t(n)}catch(t){throw console.error(`Error thrown by handler ${e} for context type ${n.type}: ${t}`),t}},ze=(t,e)=>`You have tried to to use ${t} but ${e} has not been overridden in the Interop Broker. Please override this function. Refer to our documentation for more info.`,_e=(t,e,n,i)=>{const{uuid:r,name:s}=n;return i?`Entity with identity: ${r}/${s} has called ${i} or ${t} but ${e} has not been overridden.`:`Entity with identity: ${r}/${s} has called ${t} but ${e} has not been overridden.`},qe={fireIntent:ze("fireIntent","handleFiredIntent"),fireIntentForContext:ze("fireIntentForContext","handleFiredIntentForContext"),getInfoForIntent:ze("getInfoForIntent","handleInfoForIntent"),getInfoForIntentsByContext:ze("getInfoForIntentsByContext","handleInfoForIntentsByContext"),joinSessionContextGroupWithJoinContextGroup:"The Context Group you have tried to join is a Session Context Group. Custom Context Groups can only be defined by the Interop Broker through code or manifest configuration. Please use joinSessionContextGroup.",fdc3Open:ze("fdc3.open","fdc3HandleOpen"),fdc3FindInstances:ze("fdc3.findInstances","fdc3HandleFindInstances"),fdc3GetAppMetadata:ze("fdc3.getAppMetadata","fdc3HandleGetAppMetadata"),fdc3GetInfo:ze("fdc3.getInfo","fdc3HandleGetInfo")},Je=t=>t?"object"!=typeof t?{isValid:!1,reason:"Context must be an Object"}:t.type?{isValid:!0}:{isValid:!1,reason:"Context must have a type property"}:{isValid:!1,reason:"No context supplied"};class Ye{constructor(t,e){this.provider=t,this.id=e,this.lastContext=void 0,this.contextGroupMap=new Map,this.clients=new Map,this.registerListeners()}registerListeners(){this.provider.register(`sessionContextGroup:getContext-${this.id}`,this.getCurrentContext.bind(this)),this.provider.register(`sessionContextGroup:setContext-${this.id}`,this.setContext.bind(this)),this.provider.register(`sessionContextGroup:handlerAdded-${this.id}`,this.handlerAdded.bind(this)),this.provider.register(`sessionContextGroup:handlerRemoved-${this.id}`,this.handlerRemoved.bind(this))}getCurrentContext(t){return t.type?this.contextGroupMap.get(t.type):this.lastContext}setContext(t,e){const{context:n}=t,i=Je(n);if(!1===i.isValid)throw new Error(`Failed to set Context - bad Context. Reason: ${i.reason}. Context: ${JSON.stringify(n)}`);if(!this.getClientState(e))throw new Error(`Client with Identity: ${e.uuid} ${e.name} not in Session Client State Map`);this.contextGroupMap.set(n.type,n),this.lastContext=n;Array.from(this.clients.values()).forEach(t=>{t.contextHandlers.get(n.type)?.forEach(e=>{this.provider.dispatch(t.clientIdentity,e,n)}),t.globalHandler&&this.provider.dispatch(t.clientIdentity,t.globalHandler,n)})}getClientState(t){return this.clients.get(t.endpointId)}async handlerAdded(t,e){const{handlerId:n,contextType:i}=t,r=this.getClientState(e);if(!r)throw new Error(`Client with Identity: ${e.uuid} ${e.name} not in Client State Map`);if(i){const t=r.contextHandlers.get(i)||[];r.contextHandlers.set(i,[...t,n]);const s=this.contextGroupMap.get(i);s&&await this.provider.dispatch(e,n,s)}else{r.globalHandler=n;const t=[...this.contextGroupMap.keys()].map(async t=>{const i=this.contextGroupMap.get(t);i&&await this.provider.dispatch(e,n,i)});await Promise.all(t)}}handlerRemoved(t,e){const{handlerId:n}=t,i=this.clients.get(e.endpointId);i?(Array.from(i.contextHandlers).forEach(([,t])=>{const e=t.indexOf(n);e>-1&&t.splice(e,1)}),i.globalHandler===n&&(i.globalHandler=void 0)):console.warn(`Trying to remove a handler from a client that isn't mapped. handlerId: ${n}. clientIdentity: ${e}`)}registerNewClient(t){if(!this.clients.has(t.endpointId)){const e={contextHandlers:new Map,clientIdentity:t,globalHandler:void 0};this.clients.set(t.endpointId,e)}}onDisconnection(t){this.clients.delete(t.endpointId)}}class Ke{constructor(t,e,n){this.provider=t,this.id=e,this.clients=new Map,this.registerListeners(),this.contextByContextType=new Map,this.lastContext=void 0,this.provider.onConnection(t=>this.registerNewClient(t)),this.removePrivateChannelProvider=n,this.provider.onDisconnection(async t=>{const{endpointId:e}=t;this.clients.has(e)&&await this.handleClientDisconnecting(t),0===(await this.provider.getAllClientInfo()).length&&(this.provider.destroy(),this.removePrivateChannelProvider(this.id))})}getClientState(t){return this.clients.get(t.endpointId)}registerListeners(){this.provider.register("broadcast",this.broadcast.bind(this)),this.provider.register("getCurrentContext",this.getCurrentContext.bind(this)),this.provider.register("contextHandlerAdded",this.contextHandlerAdded.bind(this)),this.provider.register("contextHandlerRemoved",this.contextHandlerRemoved.bind(this)),this.provider.register("nonStandardHandlerRemoved",this.nonStandardHandlerRemoved.bind(this)),this.provider.register("onAddContextHandlerAdded",this.onAddContextHandlerAdded.bind(this)),this.provider.register("onDisconnectHandlerAdded",this.onDisconnectHandlerAdded.bind(this)),this.provider.register("onUnsubscribeHandlerAdded",this.onUnsubscribeHandlerAdded.bind(this)),this.provider.register("clientDisconnecting",(t,e)=>{this.handleClientDisconnecting(e)})}broadcast(t,e){const{context:n}=t;if(!this.getClientState(e))throw new Error(`Client with Identity: ${e.uuid} ${e.name}, tried to call broadcast, is not connected to this Private Channel`);const i=Je(n);if(!1===i.isValid)throw new Error(`Failed to broadcast - bad Context. Reason: ${i.reason}. Context: ${JSON.stringify(n)}`);this.contextByContextType.set(n.type,n),this.lastContext=n,Array.from(this.clients.values()).forEach(t=>{const e=t.handlerIdsByContextTypes.get(n.type);e&&e.forEach(e=>{this.provider.dispatch(t.clientIdentity,e,n)}),t.globalHandler&&this.provider.dispatch(t.clientIdentity,t.globalHandler,n)})}getCurrentContext(t,e){const{contextType:n}=t;if(!this.getClientState(e))throw new Error(`Client with Identity: ${e.uuid} ${e.name}, tried to call getCurrentContext, is not connected to this Private Channel`);if(void 0!==n){const t=this.contextByContextType.get(n);return t||null}return this.lastContext?this.lastContext:null}contextHandlerAdded(t,e){const{handlerId:n,contextType:i}=t,r=this.getClientState(e);if(!r)throw new Error(`Client with Identity: ${e.uuid} ${e.name}, tried to call addContextListener, is not connected to this Private Channel`);if(i){const t=r.handlerIdsByContextTypes.get(i)||[];r.handlerIdsByContextTypes.set(i,[...t,n])}else r.globalHandler=n;Array.from(this.clients.values()).forEach(t=>{t.clientIdentity.endpointId!==e.endpointId&&t.onAddContextListenerHandlerId&&this.provider.dispatch(t.clientIdentity,t.onAddContextListenerHandlerId,i)})}async contextHandlerRemoved(t,e){const{handlerId:n}=t,i=this.getClientState(e);if(i){let t;if(i.globalHandler===n)i.globalHandler=void 0;else for(const[e,r]of i.handlerIdsByContextTypes){const i=r.indexOf(n);i>-1&&(r.splice(i,1),t=e)}const r=(await this.getConnectedClients()).map(async n=>{const{clientIdentity:i,clientIdentity:{endpointId:r},onUnsubscribeHandlerId:s}=n;r!==e.endpointId&&s&&await this.provider.dispatch(i,s,t)});try{await Promise.all(r)}catch(t){throw console.error(`Problem when attempting to dispatch to onUnsubscribeHandlers. Error: ${t} Removing Client: ${n}. uuid: ${e.uuid}. name: ${e.name}. endpointId: ${e.endpointId}`),new Error(t)}}else console.warn(`Trying to remove a handler from a client that isn't mapped. handlerId: ${n}. uuid: ${e.uuid}. name: ${e.name}. endpointId: ${e.endpointId}.`)}nonStandardHandlerRemoved(t,e){const{handlerId:n}=t,i=this.getClientState(e);i?i.onDisconnectHandlerId===n?i.onDisconnectHandlerId=void 0:i.onAddContextListenerHandlerId===n?i.onAddContextListenerHandlerId=void 0:i.onUnsubscribeHandlerId===n&&(i.onUnsubscribeHandlerId=void 0):console.warn(`Trying to remove a handler from a client that isn't mapped. handlerId: ${n}. clientIdentity: ${e}`)}onAddContextHandlerAdded(t,e){const n=this.getClientState(e),{handlerId:i}=t;if(!n)throw new Error(`Client with Identity: ${e.uuid} ${e.name}, tried to call onAddContextListener, is not connected to this Private Channel`);n.onAddContextListenerHandlerId=i,Array.from(this.clients.values()).forEach(t=>{t.clientIdentity.endpointId!==e.endpointId&&Array.from(t.handlerIdsByContextTypes.keys()).forEach(t=>{this.provider.dispatch(e,i,t)})})}onDisconnectHandlerAdded(t,e){const n=this.getClientState(e),{handlerId:i}=t;if(!n)throw new Error(`Client with Identity: ${e.uuid} ${e.name}, tried to call onDisconnect, is not connected to this Private Channel`);n.onDisconnectHandlerId=i}onUnsubscribeHandlerAdded(t,e){const n=this.getClientState(e),{handlerId:i}=t;if(!n)throw new Error(`Client with Identity: ${e.uuid} ${e.name}, tried to call onUnsubscribe, is not connected to this Private Channel`);n.onUnsubscribeHandlerId=i}removeClient(t){const e=this.getClientState(t);if(!e)throw new Error(`Client with Identity: ${t.uuid} ${t.name}, tried to call disconnect, is not connected to this Private Channel`);e.handlerIdsByContextTypes.clear(),this.clients.delete(t.endpointId)}async fireOnDisconnectForOtherClients(t){const{endpointId:e}=t,n=(await this.getConnectedClients()).map(async t=>{const{clientIdentity:{endpointId:n},onDisconnectHandlerId:i}=t;n!==e&&i&&await this.provider.dispatch(t.clientIdentity,i)});try{await Promise.all(n)}catch(e){throw console.error(`Problem when attempting to dispatch to onDisconnectHandlers. Error: ${e} Disconnecting Client: uuid: ${t.uuid}. name: ${t.name}. endpointId: ${t.endpointId}`),new Error(e)}}async unsubscribeAll(t){const{endpointId:e}=t,n=this.clients.get(e);if(n){const e=Array.from(n.handlerIdsByContextTypes.values()).flat(),i=n.globalHandler;if(e.length>0){const n=e.map(async e=>this.contextHandlerRemoved({handlerId:e},t));try{await Promise.all(n)}catch(t){console.error(t.message)}}if(i)try{await this.contextHandlerRemoved({handlerId:i},t)}catch(t){console.error(t.message)}}}async handleClientDisconnecting(t){await this.unsubscribeAll(t),this.removeClient(t),await this.fireOnDisconnectForOtherClients(t)}registerNewClient(t){if(!this.clients.has(t.endpointId)){const e={clientIdentity:t,handlerIdsByContextTypes:new Map,globalHandler:void 0,onAddContextListenerHandlerId:void 0,onUnsubscribeHandlerId:void 0,onDisconnectHandlerId:void 0};this.clients.set(t.endpointId,e)}}async getConnectedClients(){const t=await this.provider.getAllClientInfo();return Array.from(this.clients.values()).filter(e=>{const{uuid:n,name:i}=e.clientIdentity;return t.some(t=>i===t.name&&n===t.uuid)})}static init(t,e,n){return new Ke(t,e,n)}}const Ze={"fdc3.channel.1":{name:"Channel 1",color:"red",glyph:"1"},"fdc3.channel.2":{name:"Channel 2",color:"orange",glyph:"2"},"fdc3.channel.3":{name:"Channel 3",color:"yellow",glyph:"3"},"fdc3.channel.4":{name:"Channel 4",color:"green",glyph:"4"},"fdc3.channel.5":{name:"Channel 5",color:"cyan",glyph:"5"},"fdc3.channel.6":{name:"Channel 6",color:"blue",glyph:"6"},"fdc3.channel.7":{name:"Channel 7",color:"magenta",glyph:"7"},"fdc3.channel.8":{name:"Channel 8",color:"purple",glyph:"8"}},Qe={red:"fdc3.channel.1",orange:"fdc3.channel.2",yellow:"fdc3.channel.3",green:"fdc3.channel.4",teal:"fdc3.channel.5",blue:"fdc3.channel.6",pink:"fdc3.channel.7",indigo:"fdc3.channel.8",purple:"fdc3.channel.8"};var Xe,tn,en,nn=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},rn=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};const sn=Object.entries(Ze).map(([t,e])=>({id:t,displayMetadata:e}));class on extends l{constructor(t,e,n){super(t),Xe.set(this,void 0),tn.set(this,void 0),en.set(this,void 0),this.getProvider=()=>rn(this,en,"f").getValue(),this.interopClients=new Map,this.contextGroupsById=new Map,nn(this,tn,n.contextGroups??[...sn],"f"),nn(this,Xe,n.fdc3Info,"f"),n?.logging&&(this.logging=n.logging),this.intentClientMap=new Map,this.lastContextMap=new Map,this.sessionContextGroupMap=new Map,this.privateChannelProviderMap=new Map,nn(this,en,new A(e),"f"),this.setContextGroupMap(),this.setupChannelProvider()}static createClosedConstructor(...t){return class extends on{constructor(...n){if(n.length){const[i,r,s]=n;if(s&&"object"==typeof s&&!e(s,t[2]))return console.warn("You have modified the parameters of the InteropOverride constructor. This behavior is deprecated and will be removed in a future version. You can modify these options in your manifest. Please consult our Interop docs for guidance on migrating to the new override scheme."),void super(t[0],t[1],s);console.warn("You are attempting to pass arguments to the InteropOverride constructor. This is not necessary, and these passed arguments will be ignored. You are likely using an older InteropBroker override scheme. Please consult our Interop docs for guidance on migrating to the new override scheme.")}super(...t)}}}setContext({context:t},e){this.wire.sendAction("interop-broker-set-context").catch(t=>{});const n=this.getClientState(e);if(!n||!n.contextGroupId)throw n?new Error("You must join a context group before you can set context."):new Error(`Client with Identity: ${e.uuid} ${e.name} not in Client State Map`);{const{contextGroupId:e}=n;this.setContextForGroup({context:t},e)}}setContextForGroup({context:t},e){this.wire.sendAction("interop-broker-set-context-for-group").catch(t=>{});const n=this.normalizeContextGroupId(e);if(void 0===n)return;const i=this.contextGroupsById.get(n);if(!i)throw new Error(`Unable to set context for context group that isn't in the context group mapping: ${n}.`);const r=on.checkContextIntegrity(t);if(!1===r.isValid)throw new Error(`Failed to set Context - bad Context. Reason: ${r.reason}. Context: ${JSON.stringify(t)}`);const s=t.type;i.set(s,t),this.lastContextMap.set(n,s);Array.from(this.interopClients.values()).filter(t=>t.contextGroupId===n).forEach(e=>{for(const[,n]of e.contextHandlers)on.isContextTypeCompatible(s,n.contextType)&&this.invokeContextHandler(e.clientIdentity,n.handlerId,t)})}getCurrentContext(t,e){this.wire.sendAction("interop-broker-get-current-context").catch(t=>{});const n=this.getClientState(e);if(!n?.contextGroupId)throw new Error("You must be a member of a context group to call getCurrentContext");const{contextGroupId:i}=n,r=this.contextGroupsById.get(i),s=this.lastContextMap.get(i),o=t?.contextType??s;return r&&o?r.get(o):void 0}async joinContextGroup({contextGroupId:t,target:e},n){this.wire.sendAction("interop-broker-join-context-group").catch(t=>{});const i=this.normalizeContextGroupId(t);if(void 0!==i){if(this.sessionContextGroupMap.has(i))throw new Error(qe.joinSessionContextGroupWithJoinContextGroup);if(e){on.hasEndpointId(e)&&await this.addClientToContextGroup({contextGroupId:i},e);try{const t=this.channel.connections.filter(t=>t.uuid===e.uuid&&t.name===e.name);if(!t.length)throw new Error(`Given Identity ${e.uuid} ${e.name} is not connected to the Interop Broker.`);t.length>1&&console.warn(`More than one connection found for identity ${e.uuid} ${e.name}`);const n=[];for(const e of t)n.push(this.addClientToContextGroup({contextGroupId:i},e));await Promise.all(n)}catch(t){throw new Error(t)}}else await this.addClientToContextGroup({contextGroupId:i},n)}else e?await this.removeFromContextGroup({target:e},n):await this.removeClientFromContextGroup(n)}async addClientToContextGroup({contextGroupId:t},e){this.wire.sendAction("interop-broker-add-client-to-context-group").catch(t=>{});const n=this.normalizeContextGroupId(t);if(void 0===n)return void await this.removeClientFromContextGroup(e);const i=this.getClientState(e);if(!i)throw new Error(`Client with Identity: ${e.uuid} ${e.name} not in Client State Map`);if(!this.getContextGroups().find(t=>t.id===n))throw new Error(`Attempting to join a context group that does not exist: ${n}. You may only join existing context groups.`);const r=i.contextGroupId;if(r!==n){i.contextGroupId=n,await this.setCurrentContextGroupInClientOptions(e,n);const t=this.contextGroupsById.get(n);for(const[,n]of i.contextHandlers){const{contextType:i,handlerId:r}=n;if(void 0===i)t.forEach((t,n)=>{this.invokeContextHandler(e,r,t)});else if(t.has(i)){const n=t.get(i);n&&this.invokeContextHandler(e,r,n)}}Promise.allSettled(this.channel.publish("client-changed-context-group",{identity:e,contextGroupId:n,previousContextGroupId:r||null}))}}async removeFromContextGroup({target:t},e){if(this.wire.sendAction("interop-broker-remove-from-context-group").catch(t=>{}),t){on.hasEndpointId(t)&&await this.removeClientFromContextGroup(t);try{const e=this.channel.connections.filter(e=>e.uuid===t.uuid&&e.name===t.name);if(!e.length)throw new Error(`No connection found for given Identity ${t.uuid} ${t.name}`);e.length>1&&console.warn(`More than one connection found for identity ${t.uuid} ${t.name}`);const n=[];for(const t of e)n.push(this.removeClientFromContextGroup(t));await Promise.all(n)}catch(t){throw new Error(t)}}else await this.removeClientFromContextGroup(e)}async removeClientFromContextGroup(t){this.wire.sendAction("interop-broker-remove-client-from-context-group").catch(t=>{});const e=this.getClientState(t),n=e?.contextGroupId;e&&(e.contextGroupId=void 0),await this.setCurrentContextGroupInClientOptions(t,null),void 0!==n&&Promise.allSettled(this.channel.publish("client-changed-context-group",{identity:t,contextGroupId:null,previousContextGroupId:n||null}))}getContextGroups(){return this.wire.sendAction("interop-broker-get-context-groups").catch(t=>{}),rn(this,tn,"f").map(t=>({...t}))}getInfoForContextGroup({contextGroupId:t}){this.wire.sendAction("interop-broker-get-info-for-context-group").catch(t=>{});const e=this.normalizeContextGroupId(t);if(void 0!==e)return this.getContextGroups().find(t=>t.id===e)}getAllClientsInContextGroup({contextGroupId:t}){this.wire.sendAction("interop-broker-get-all-clients-in-context-group").catch(t=>{});const e=this.normalizeContextGroupId(t);if(void 0===e)return[];return Array.from(this.interopClients.values()).filter(t=>t.contextGroupId===e).map(t=>t.clientIdentity)}async handleFiredIntent(t,e){const n=_e("fdc3.raiseIntent","InteropBroker.handleFiredIntent",e,"interopClient.fireIntent");throw console.warn(n),new Error(qe.fireIntent)}async setIntentTarget(t,e){this.wire.sendAction("interop-broker-set-intent-target").catch(t=>{});const n=this.intentClientMap.get(e.name),i=`intent-handler-${t.name}`;if(n){const e=n.get(i);if(e){if(e.pendingIntents.push(t),e.clientIdentity&&e.isReady){const{clientIdentity:t,pendingIntents:n}=e;try{const r=n[n.length-1];await this.invokeIntentHandler(t,i,r),e.pendingIntents=[]}catch(n){console.error(`Error invoking intent handler for client ${t.uuid}/${t.name}/${t.endpointId}`),e.isReady=!1}}}else n.set(i,{isReady:!1,pendingIntents:[t]})}else{this.intentClientMap.set(e.name,new Map);const n=this.intentClientMap.get(e.name);n&&n.set(i,{isReady:!1,pendingIntents:[t]})}}async handleInfoForIntent(t,e){const n=_e("fdc3.findIntent","InteropBroker.handleInfoForIntent",e,"interopClient.getInfoForIntent");throw console.warn(n),new Error(qe.getInfoForIntent)}async handleInfoForIntentsByContext(t,e){const n=_e("fdc3.findIntentsByContext","InteropBroker.handleInfoForIntentsByContext",e,"interopClient.getInfoForIntentsByContext");throw console.warn(n),new Error(qe.getInfoForIntentsByContext)}async handleFiredIntentForContext(t,e){const n=_e("fdc3.raiseIntentForContext","InteropBroker.handleFiredIntentForContext",e,"interopClient.fireIntentForContext");throw console.warn(n),new Error(qe.fireIntentForContext)}async clientDisconnected(t){}async fdc3HandleOpen({app:t,context:e},n){const i=_e("fdc3.open","InteropBroker.fdc3HandleOpen",n);throw console.warn(i),new Error(qe.fdc3Open)}async fdc3HandleFindInstances(t,e){const n=_e("fdc3.open","InteropBroker.fdc3HandleFindInstances",e);throw console.warn(n),new Error(qe.fdc3FindInstances)}async fdc3HandleGetAppMetadata(t,e){const n=_e("fdc3.getAppMetadata","InteropBroker.fdc3HandleGetAppMetadata",e);throw console.warn(n),new Error(qe.fdc3GetAppMetadata)}async invokeContextHandler(t,e,n){const i=await this.getProvider();try{await i.dispatch(t,e,n)}catch(i){console.error(`Error invoking context handler ${e} for context type ${n.type} in client ${t.uuid}/${t.name}/${t.endpointId}`,i)}}async invokeIntentHandler(t,e,n){const i=await this.getProvider();await i.dispatch(t,e,n)}async fdc3HandleGetInfo(t,e){const{fdc3Version:n}=t;return{fdc3Version:n,...rn(this,Xe,"f"),optionalFeatures:{OriginatingAppMetadata:!1,UserChannelMembershipAPIs:!0},appMetadata:{appId:"",instanceId:""}}}async getAllClientInfo(){return(await this.getProvider()).getAllClientInfo()}decorateSnapshot(t){return{...t,interopSnapshotDetails:{contextGroupStates:this.getContextGroupStates()}}}applySnapshot(t,e){const n=t?.interopSnapshotDetails?.contextGroupStates;if(n){const t=this.normalizeContextGroupStates(n);e?.closeExistingWindows||this.updateExistingClients(t),this.rehydrateContextGroupStates(t)}}updateExistingClients(t){this.interopClients.forEach(e=>{const{clientIdentity:n,contextGroupId:i,contextHandlers:r}=e;if(i){const e=t[i];for(const[,t]of Object.entries(e))r.forEach(e=>{const{handlerId:i,contextType:r}=e;on.isContextTypeCompatible(t.type,r)&&this.invokeContextHandler(n,i,t)})}})}getContextGroupStates(){return on.toObject(this.contextGroupsById)}rehydrateContextGroupStates(t){const e=Object.entries(t);for(const[t,n]of e){const e=Object.entries(n);for(const[n,i]of e)if(this.contextGroupsById.has(t)){this.contextGroupsById.get(t).set(n,i)}else console.warn(`Attempting to set a context group that isn't in the context group mapping. Skipping context group rehydration for: ${t}`)}}contextHandlerRegistered({contextType:t,handlerId:e},n){const i={contextType:t,handlerId:e},r=this.getClientState(n);if(r?.contextHandlers.set(e,i),r&&r.contextGroupId){const{contextGroupId:i}=r,s=this.contextGroupsById.get(i);if(void 0===t)s.forEach((t,i)=>{this.invokeContextHandler(n,e,t)});else if(s.has(t)){const i=s.get(t);i&&this.invokeContextHandler(n,e,i)}}}async intentHandlerRegistered(t,e){const{handlerId:n}=t,i=this.intentClientMap.get(e.name),r=i?.get(n);if(i)if(r){const{pendingIntents:t}=r;r.clientIdentity=e,r.isReady=!0;try{if(t.length>0){const i=t[t.length-1];await this.invokeIntentHandler(e,n,i),r.pendingIntents=[]}}catch(t){console.error(`Error invoking intent handler: ${n} for client ${e.uuid}/${e.name}/${e.endpointId}`)}}else i.set(n,{isReady:!0,pendingIntents:[],clientIdentity:e});else{this.intentClientMap.set(e.name,new Map);const t=this.intentClientMap.get(e.name);t&&t.set(n,{isReady:!0,pendingIntents:[],clientIdentity:e})}}removeContextHandler({handlerId:t},e){const n=this.getClientState(e);n&&n.contextHandlers.delete(t)}handleJoinSessionContextGroup({sessionContextGroupId:t},e){try{if(!t)throw new Error("Failed to join session context group: must specify group id.");const n=this.sessionContextGroupMap.get(t);if(n)n.registerNewClient(e);else{const n=new Ye(this.channel,t);n.registerNewClient(e),this.sessionContextGroupMap.set(t,n)}return{hasConflict:this.contextGroupsById.has(t)}}catch(t){throw new Error(t)}}getClientState(t){return this.interopClients.get(t.endpointId)}static toObject(t){const e=Object.fromEntries(t),n={};return Object.entries(e).forEach(([t,e])=>{const i=Object.fromEntries(e);n[t]=i}),n}normalizeContextGroupStates(t){const e={};for(const[n,i]of Object.entries(t)){const t=this.normalizeContextGroupId(n);void 0!==t&&(e[t]={...e[t],...i})}return e}normalizeContextGroupId(t){return Object.keys(Ze).every(t=>this.contextGroupsById.has(t))?function(t){if("gray"!==t)return Object.prototype.hasOwnProperty.call(Qe,t)?Qe[t]:t}(t):t}static hasEndpointId(t){return void 0!==t.endpointId}static isContextTypeCompatible(t,e){return void 0===e||t===e}setContextGroupMap(){for(const t of this.getContextGroups())this.contextGroupsById.set(t.id,new Map)}async setCurrentContextGroupInClientOptions(t,e){try{const n=await this.fin.System.getEntityInfo(t.uuid,t.name);let i;"view"===n.entityType?i=await this.fin.View.wrap(t):"window"===n.entityType&&(i=await this.fin.Window.wrap(t)),i&&await i.updateOptions({interop:{currentContextGroup:e}})}catch(t){}}async setupChannelProvider(){try{const t=await this.getProvider();this.channel=t,this.wireChannel(t)}catch(t){throw new Error(`Error setting up Interop Broker Channel Provider: ${t}`)}}wireChannel(t){t.onConnection(async(t,e)=>{if(!await this.isConnectionAuthorized(t,e))throw new Error(`Connection not authorized for ${t.uuid}, ${t.name}`);if(!t.endpointId)throw new Error("Version too old to be compatible with Interop. Please upgrade your runtime to a more recent version.");const n={contextGroupId:void 0,contextHandlers:new Map,clientIdentity:t},i=e?.currentContextGroup?this.normalizeContextGroupId(e.currentContextGroup):void 0;i&&this.contextGroupsById.has(i)&&(n.contextGroupId=i,i!==e.currentContextGroup&&await this.setCurrentContextGroupInClientOptions(t,i)),this.interopClients.set(t.endpointId,n)}),t.onDisconnection(t=>{this.interopClients.delete(t.endpointId);const e=this.intentClientMap.get(t.name);e&&t.uuid===this.fin.me.uuid&&e.forEach(t=>{t.isReady=!1}),this.sessionContextGroupMap.forEach(e=>{e.onDisconnection(t)}),this.clientDisconnected(t)}),t.beforeAction(async(t,e,n)=>{if(!await this.isActionAuthorized(t,e,n))throw new Error(`Action (${t}) not authorized for ${n.uuid}, ${n.name}`);this.logging?.beforeAction?.enabled&&console.log(t,e,n)}),t.afterAction((t,e,n)=>{if(this.logging?.afterAction?.enabled){const i=e?[t,e,n]:[t,n];console.log(...i)}}),t.register("setContext",this.setContext.bind(this)),t.register("fireIntent",this.handleFiredIntent.bind(this)),t.register("getCurrentContext",this.getCurrentContext.bind(this)),t.register("getInfoForIntent",this.handleInfoForIntent.bind(this)),t.register("getInfoForIntentsByContext",this.handleInfoForIntentsByContext.bind(this)),t.register("fireIntentForContext",this.handleFiredIntentForContext.bind(this)),t.register("getContextGroups",this.getContextGroups.bind(this)),t.register("joinContextGroup",this.joinContextGroup.bind(this)),t.register("removeFromContextGroup",this.removeFromContextGroup.bind(this)),t.register("getAllClientsInContextGroup",this.getAllClientsInContextGroup.bind(this)),t.register("getInfoForContextGroup",this.getInfoForContextGroup.bind(this)),t.register("contextHandlerRegistered",this.contextHandlerRegistered.bind(this)),t.register("intentHandlerRegistered",this.intentHandlerRegistered.bind(this)),t.register("removeContextHandler",this.removeContextHandler.bind(this)),t.register("sessionContextGroup:createIfNeeded",this.handleJoinSessionContextGroup.bind(this)),t.register("fdc3Open",this.fdc3HandleOpen.bind(this)),t.register("fdc3v2FindIntentsByContext",this.handleInfoForIntentsByContext.bind(this)),t.register("fdc3FindInstances",this.fdc3HandleFindInstances.bind(this)),t.register("fdc3GetAppMetadata",this.fdc3HandleGetAppMetadata.bind(this)),t.register("fdc3v2GetInfo",async(t,e)=>this.fdc3HandleGetInfo.bind(this)(t,e)),t.register("createPrivateChannelProvider",async t=>{const{channelId:e}=t,n=await this.fin.InterApplicationBus.Channel.create(e),i=Ke.init(n,e,t=>{this.privateChannelProviderMap.delete(t)});this.privateChannelProviderMap.set(e,i)}),t.register("isIdUsedByPrivateChannel",async t=>{const{channelId:e}=t;return this.privateChannelProviderMap.has(e)})}isConnectionAuthorized(t,e){return this.wire.sendAction("interop-broker-is-connection-authorized").catch(t=>{}),Promise.resolve(!0)}isActionAuthorized(t,e,n){return this.wire.sendAction("interop-broker-is-action-authorized").catch(t=>{}),Promise.resolve(!0)}}Xe=new WeakMap,tn=new WeakMap,en=new WeakMap,on.checkContextIntegrity=Je;var an,cn=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},dn=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};an=new WeakMap;var hn,ln,pn,un,wn,yn,fn,gn,mn=class extends l{constructor(t,e,n){super(t),an.set(this,void 0),this.id=n,cn(this,an,e,"f")}async setContext(t){this.wire.sendAction("interop-session-context-group-set-context").catch(t=>{});return(await dn(this,an,"f")).dispatch(`sessionContextGroup:setContext-${this.id}`,{sessionContextGroupId:this.id,context:t})}async getCurrentContext(t){this.wire.sendAction("interop-session-context-group-get-context").catch(t=>{});return(await dn(this,an,"f")).dispatch(`sessionContextGroup:getContext-${this.id}`,{sessionContextGroupId:this.id,type:t})}async addContextHandler(t,e){if(this.wire.sendAction("interop-session-context-group-add-handler").catch(t=>{}),"function"!=typeof t)throw new Error("Non-function argument passed to the first parameter 'handler'. Be aware that the argument order does not match the FDC3 standard.");const n=await dn(this,an,"f");let i;return i=e?`sessionContextHandler:invoke-${this.id}-${e}-${De()}`:`sessionContextHandler:invoke-${this.id}`,n.register(i,Ue(t,i)),await n.dispatch(`sessionContextGroup:handlerAdded-${this.id}`,{handlerId:i,contextType:e}),{unsubscribe:await this.createUnsubscribeCb(i)}}async createUnsubscribeCb(t){const e=await dn(this,an,"f");return async()=>{e.remove(t),await e.dispatch(`sessionContextGroup:handlerRemoved-${this.id}`,{handlerId:t})}}getUserInstance(){return{id:this.id,setContext:Ve(this.setContext.bind(this),"Failed to set context: "),getCurrentContext:Ve(this.getCurrentContext.bind(this),"Failed to get context: "),addContextHandler:Ve(this.addContextHandler.bind(this),"Failed to add context handler: ")}}},vn=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},Cn=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class In{constructor(t){ln.set(this,void 0),pn.set(this,!1),wn.set(this,async()=>{const t=await Cn(this,ln,"f");let e=Cn(hn,hn,"f",un).get(t);return e||(e={},Cn(hn,hn,"f",un).set(t,e)),e}),yn.set(this,t=>{const e=[];let n;const i=t=>{e.forEach(e=>e(t))};return{callbacks:e,dispose:async n=>{const i=e.indexOf(n);if(i>=0&&(e.splice(i,1),0===e.length)){(await Cn(this,ln,"f")).remove(t)}},waitForRegistration:async()=>{n||(n=(async()=>{const e=await Cn(this,ln,"f");await e.register(t,i)})()),await n}}}),fn.set(this,async t=>(await Cn(this,wn,"f").call(this))[t]),gn.set(this,async t=>{const e=await Cn(this,wn,"f").call(this);return await Cn(this,fn,"f").call(this,t)||(e[t]=Cn(this,yn,"f").call(this,t)),e[t]}),this.addListener=async(t,e)=>{const n=await Cn(this,gn,"f").call(this,t);n.callbacks.push(e),await n.waitForRegistration()},this.removeListener=async(t,e)=>{if(!Cn(this,pn,"f"))return;if(await Cn(this,fn,"f").call(this,t)){const n=await Cn(this,gn,"f").call(this,t);await n.dispose(e)}},vn(this,ln,t,"f"),Promise.resolve(t).then(()=>{vn(this,pn,!0,"f")}).catch(()=>{console.warn("Channel Connection error occurred in channel client. Channel-events registrations will fail.")})}}hn=In,ln=new WeakMap,pn=new WeakMap,wn=new WeakMap,yn=new WeakMap,fn=new WeakMap,gn=new WeakMap,un={value:new WeakMap};var bn,xn,An,En,Pn=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},Mn=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class Sn extends l{constructor(t,e,n){super(t),bn.set(this,void 0),xn.set(this,void 0),An.set(this,void 0),En.set(this,void 0),this.addListener=async(t,e)=>{try{await Mn(this,En,"f").addListener(t,e)}catch(e){throw new Error(`An unexpected error occurred when adding a listener to the event ${t}. \n${e.stack}.`)}},this.removeListener=async(t,e)=>{try{await Mn(this,En,"f").removeListener(t,e)}catch(e){throw new Error(`An unexpected error occurred when removing a listener for the event ${t}. \n${e.stack}.`)}},Pn(this,xn,new Map,"f"),Pn(this,bn,e,"f"),Pn(this,An,n,"f"),Pn(this,En,new In(e),"f")}async setContext(t){this.wire.sendAction("interop-client-set-context").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("setContext",{context:t})}async addContextHandler(t,e){if(this.wire.sendAction("interop-client-add-context-handler").catch(t=>{}),"function"!=typeof t)throw new Error("Non-function argument passed to the first parameter 'handler'. Be aware that the argument order does not match the FDC3 standard.");const n=await Mn(this,bn,"f");let i;i=e?`invokeContextHandler-${e}-${De()}`:"invokeContextHandler";const r=Ue(t,i);return n.register(i,r),await n.dispatch("contextHandlerRegistered",{handlerId:i,contextType:e}),{unsubscribe:async()=>{n.remove(i),await n.dispatch("removeContextHandler",{handlerId:i})}}}async getContextGroups(){this.wire.sendAction("interop-client-get-context-groups").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("getContextGroups")}async joinContextGroup(t,e){this.wire.sendAction("interop-client-join-context-group").catch(t=>{});const n=await Mn(this,bn,"f");if(!t)throw new Error("No contextGroupId specified for joinContextGroup.");return n.dispatch("joinContextGroup",{contextGroupId:t,target:e})}async removeFromContextGroup(t){this.wire.sendAction("interop-client-remove-from-context-group").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("removeFromContextGroup",{target:t})}async getAllClientsInContextGroup(t){this.wire.sendAction("interop-client-get-all-clients-in-context-group").catch(t=>{});const e=await Mn(this,bn,"f");if(!t)throw new Error("No contextGroupId specified for getAllClientsInContextGroup.");return e.dispatch("getAllClientsInContextGroup",{contextGroupId:t})}async getInfoForContextGroup(t){this.wire.sendAction("interop-client-get-info-for-context-group").catch(t=>{});const e=await Mn(this,bn,"f");if(!t)throw new Error("No contextGroupId specified for getInfoForContextGroup.");return e.dispatch("getInfoForContextGroup",{contextGroupId:t})}async fireIntent(t){this.wire.sendAction("interop-client-fire-intent").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("fireIntent",t)}async registerIntentHandler(t,e,n){this.wire.sendAction("interop-client-register-intent-handler").catch(t=>{});const i=await Mn(this,bn,"f"),r=`intent-handler-${e}`,s=((t,e)=>async n=>{try{return t(n)}catch(t){throw console.error(`Error thrown by handler ${e}: ${t}`),t}})(t,r);try{await i.register(r,s),await i.dispatch("intentHandlerRegistered",{handlerId:r,...n})}catch(t){throw new Error("Unable to register intent handler")}return{unsubscribe:async()=>{i.remove(r)}}}async getCurrentContext(t){this.wire.sendAction("interop-client-get-current-context").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("getCurrentContext",{contextType:t})}async getInfoForIntent(t){this.wire.sendAction("interop-client-get-info-for-intent").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("getInfoForIntent",t)}async getInfoForIntentsByContext(t){this.wire.sendAction("interop-client-get-info-for-intents-by-context").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("getInfoForIntentsByContext",t)}async fireIntentForContext(t){this.wire.sendAction("interop-client-fire-intent-for-context").catch(t=>{});return(await Mn(this,bn,"f")).dispatch("fireIntentForContext",t)}async joinSessionContextGroup(t){try{const e=Mn(this,xn,"f").get(t);if(e)return e.getUserInstance();const n=await Mn(this,bn,"f"),{hasConflict:i}=await n.dispatch("sessionContextGroup:createIfNeeded",{sessionContextGroupId:t});i&&console.warn(`A (non-session) context group with the name "${t}" already exists. If you are trying to join a Context Group, call joinContextGroup instead.`);const r=new mn(this.wire,Mn(this,bn,"f"),t);return Mn(this,xn,"f").set(t,r),r.getUserInstance()}catch(e){throw console.error(`Error thrown trying to create Session Context Group with id "${t}": ${e}`),e}}async onDisconnection(t){this.wire.sendAction("interop-client-add-ondisconnection-listener").catch(t=>{});return(await Mn(this,bn,"f")).onDisconnection(e=>{const{uuid:n}=e;t({type:"interop-broker",topic:"disconnected",brokerName:n})})}getFDC3Sync(t){return Mn(this,An,"f").call(this,t,this,this.wire)}async getFDC3(t){return this.getFDC3Sync(t)}static async ferryFdc3Call(t,e,n){return(await Mn(t,bn,"f")).dispatch(e,n||null)}}function kn(t,e){if(e&&"2.0"===e){const e=function(t){return["fdc3HandleFindInstances","handleInfoForIntent","handleInfoForIntentsByContext","fdc3HandleGetAppMetadata","fdc3HandleGetInfo","fdc3HandleOpen","handleFiredIntent","handleFiredIntentForContext"].filter(e=>t[e]===on.prototype[e])}(t);e.length>0&&console.warn(`WARNING: FDC3 2.0 has been set as a default option for Views in this Platform, but the required InteropBroker APIs for FDC3 2.0 compliance have not all been overridden.\nThe following APIs need to be overridden:\n${e.join("\n")}`)}}bn=new WeakMap,xn=new WeakMap,An=new WeakMap,En=new WeakMap;class Tn{constructor(t,e){this.id=e,this.client=t,this.listeners=new Map}async broadcast(t){return this.client.dispatch("broadcast",{context:t})}async getCurrentContext(t){return this.client.dispatch("getCurrentContext",{contextType:t})}async addContextListener(t,e){if("function"!=typeof e)throw new Error("Non-function argument passed to the second parameter 'handler'. Be aware that the argument order does not match the FDC3 standard.");let n;n=t?`contextHandler:invoke-${this.id}-${t}-${De()}`:`contextHandler:invoke-${this.id}-${De()}`,this.client.register(n,Ue(e,n));const i={unsubscribe:await this.createContextUnsubscribeCb(n)};return this.listeners.set(n,i),await this.client.dispatch("contextHandlerAdded",{handlerId:n,contextType:t}),i}createNonStandardUnsubscribeCb(t){return async()=>{this.client.remove(t),this.listeners.delete(t),await this.client.dispatch("nonStandardHandlerRemoved",{handlerId:t})}}createContextUnsubscribeCb(t){return async()=>{this.client.remove(t),this.listeners.delete(t),await this.client.dispatch("contextHandlerRemoved",{handlerId:t})}}onAddContextListener(t){const e=`onContextHandlerAdded:invoke-${this.id}-${De()}`;this.client.register(e,t);const n={unsubscribe:this.createNonStandardUnsubscribeCb(e)};return this.listeners.set(e,n),this.client.dispatch("onAddContextHandlerAdded",{handlerId:e}),n}onDisconnect(t){const e=`onDisconnect:invoke-${this.id}-${De()}`;this.client.register(e,t);const n={unsubscribe:this.createNonStandardUnsubscribeCb(e)};return this.listeners.set(e,n),this.client.dispatch("onDisconnectHandlerAdded",{handlerId:e}),n}onUnsubscribe(t){const e=`onUnsubscribe:invoke-${this.id}-${De()}`;this.client.register(e,t);const n={unsubscribe:this.createNonStandardUnsubscribeCb(e)};return this.listeners.set(e,n),this.client.dispatch("onUnsubscribeHandlerAdded",{handlerId:e}),n}async cleanUpAllSubs(){Array.from(this.listeners.keys()).forEach(t=>{this.client.remove(t),this.listeners.delete(t)})}async disconnect(){try{await this.client.dispatch("clientDisconnecting"),await this.cleanUpAllSubs(),await this.client.disconnect()}catch(t){throw new Error(t.message)}}}const Ln=t=>({id:t.id,type:"app",broadcast:t.setContext,getCurrentContext:async e=>{const n=await t.getCurrentContext(e);return void 0===n?null:n},addContextListener:(n,i)=>{let r,s;"function"==typeof n?(console.warn("addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)"),r=n):(r=i,"string"==typeof n&&(s=n));const o=(async()=>{let n=!0;const i=await t.getCurrentContext(s);return t.addContextHandler((t,s)=>{if(!n||(n=!1,!e(i,t)))return r(t,s)},s)})();return{...o,unsubscribe:()=>o.then(t=>t.unsubscribe())}}}),$n=t=>{const e=Ln(t);return{...e,addContextListener:async(...t)=>e.addContextListener(...t)}},Fn=t=>({addContextListener:()=>{throw new Gn("Channel.addContextListener",t)},broadcast:()=>{throw new Gn("Channel.broadcast",t)},getCurrentContext:()=>{throw new Gn("Channel.getCurrentContext",t)}});class Gn extends Error{constructor(t,e="System"){super(t),this.message=`Calling ${t} on an instance of a ${e} Channel returned by fdc3.get${e}Channels is not supported. If you would like to use a ${e} Channel, please use fdc3.joinChannel, fdc3.addContextListener, and fdc3.broadcast instead.`}}var Rn,On;!function(t){t.NoResultReturned="NoResultReturned",t.IntentHandlerRejected="IntentHandlerRejected"}(Rn||(Rn={})),function(t){t.NoChannelFound="NoChannelFound",t.AccessDenied="AccessDenied",t.CreationFailed="CreationFailed"}(On||(On={}));const Wn=t=>{let e=!1;const n=()=>{if(e)throw new Error("Private Channel Client has been disconnected from the Private Channel")};return{id:t.id,type:"private",broadcast:async e=>(n(),t.broadcast(e)),getCurrentContext:async e=>(n(),t.getCurrentContext(e)),addContextListener:async(e,i)=>{n();let r=i,s=e;"function"==typeof e&&(console.warn("addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)"),r=e,s=null);return t.addContextListener(s,r)},onAddContextListener:e=>(n(),t.onAddContextListener(e)),disconnect:async()=>(n(),e=!0,t.disconnect()),onDisconnect:e=>(n(),t.onDisconnect(e)),onUnsubscribe:e=>(n(),t.onUnsubscribe(e))}},jn=async(t,e,n,i)=>{const r=De(),s=n?{target:n,intentResolutionResultId:r}:{intentResolutionResultId:r},o=i?{name:i,context:e,metadata:s}:{...e,metadata:s},a=new Promise((e,n)=>{fin.InterApplicationBus.subscribe({uuid:"*"},r,t=>{e(t)}).catch(()=>{"other"===t.wire.environment.type&&e(void 0),n(new Error("getResult is not supported in this environment"))})}),c=async()=>{let e=await a;if(null==e)return;if("object"!=typeof e)throw new Error(Rn.NoResultReturned);const{error:n}=e;if(n)throw new Error(Rn.IntentHandlerRejected);if((t=>{if(t&&"object"==typeof t&&"type"in t&&"id"in t){const{type:e,id:n}=t;return"string"==typeof e&&"string"==typeof n&&("app"===e||"private"===e)}return!1})(e)){const{id:n,type:i}=e;switch(i){case"private":e=await(async t=>{try{const e=await fin.InterApplicationBus.Channel.connect(t),n=new Tn(e,t);return Wn(n)}catch(e){throw new Error(`Private Channel with id: ${t} doesn't exist`)}})(n);break;case"app":{const i=await t.joinSessionContextGroup(n);e=$n(i);break}}}else if(!(t=>{if(t&&"object"==typeof t&&"type"in t){const{type:e}=t;return"string"==typeof e}return!1})(e))throw new Error(Rn.NoResultReturned);return e},d=i?await t.fireIntent(o):await t.fireIntentForContext(o);return"object"!=typeof d?{source:{appId:"",instanceId:""},intent:"",version:"2.0",getResult:c}:{...d,getResult:c}};var Nn,Hn=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)},Bn=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n};class Dn{get client(){return Hn(this,Nn,"f").call(this)}get fin(){return this.wire.getFin()}constructor(t,e){this.wire=e,Nn.set(this,void 0),Bn(this,Nn,t,"f")}async broadcast(t){return this.wire.recordAnalytic("fdc3-broadcast"),this.client.setContext(t)}async _open(t,e){this.wire.recordAnalytic("fdc3-open");try{return await Sn.ferryFdc3Call(this.client,"fdc3Open",{app:t,context:e})}catch(t){const e=t.message===qe.fdc3Open?"ResolverUnavailable":t.message;throw new Error(e)}}async _getChannels(){return(await this.client.getContextGroups()).map(t=>({...t,type:"system",...Fn()}))}async getOrCreateChannel(t,e){this.wire.recordAnalytic("fdc3-get-or-create-channel");if(await Sn.ferryFdc3Call(this.client,"isIdUsedByPrivateChannel",{channelId:t}))throw new Error(On.AccessDenied);const n=(await this._getChannels()).find(e=>e.id===t);if(n)return{...n,type:"system",...Fn()};try{return e(await this.client.joinSessionContextGroup(t))}catch(t){throw console.error(t.message),new Error(On.CreationFailed)}}async getSystemChannels(){return this.wire.recordAnalytic("fdc3-get-system-channels"),this._getChannels()}async joinChannel(t){this.wire.recordAnalytic("fdc3-join-channel");try{if(!await this.client.getInfoForContextGroup(t))throw console.error(`No User Channel was found with the ID "${t}". If this is an App Channel, use getOrCreateChannel instead.`),new Error(On.NoChannelFound);return await this.client.joinContextGroup(t)}catch(t){if(t.message===On.NoChannelFound)throw new Error(On.NoChannelFound);if(console.error(t.message),t.message.startsWith("Attempting to join a context group that does not exist"))throw new Error(On.NoChannelFound);throw new Error(On.AccessDenied)}}async getCurrentChannel(){this.wire.recordAnalytic("fdc3-get-current-channel");const t=await this.getCurrentContextGroupInfo();return t?this.buildChannelObject(t):null}async leaveCurrentChannel(){return this.wire.recordAnalytic("fdc3-leave-current-channel"),this.client.removeFromContextGroup()}async getCurrentContextGroupInfo(){const t=await this.client.getContextGroups(),e=t.map(async t=>this.client.getAllClientsInContextGroup(t.id));return t[(await Promise.all(e)).findIndex(t=>t.some(t=>{const{uuid:e,name:n}=t;return this.wire.me.uuid===e&&this.wire.me.name===n}))]}async buildChannelObject(t){return{...t,type:"system",addContextListener:(...[t,n])=>{let i,r;"function"==typeof t?(console.warn("addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)"),i=t):(i=n,"string"==typeof t&&(r=t));const s=(async()=>{let t=!0;const n=await this.client.getCurrentContext(r);return this.client.addContextHandler((r,s)=>{if(!t||(t=!1,!e(n,r)))return i(r,s)},r)})();return{...s,unsubscribe:()=>s.then(t=>t.unsubscribe())}},broadcast:this.broadcast.bind(this),getCurrentContext:async t=>{const e=await this.client.getCurrentContext(t);return void 0===e?null:e}}}}Nn=new WeakMap;class Vn extends Dn{async open(t,e){await super._open(t,e)}addContextListener(t,e){let n;return this.wire.recordAnalytic("fdc3-add-context-listener"),"function"==typeof t?(console.warn("addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)"),n=this.client.addContextHandler(t)):n=this.client.addContextHandler(e,null===t?void 0:t),{...n,unsubscribe:()=>n.then(t=>t.unsubscribe())}}addIntentListener(t,e){this.wire.recordAnalytic("fdc3-add-intent-listener");const n=this.client.registerIntentHandler(t=>{const{context:n,metadata:i}=t,{metadata:r}=n,s=i?.intentResolutionResultId||r?.intentResolutionResultId;s&&this.fin.InterApplicationBus.publish(s,null).catch(()=>null),e(t.context)},t,{fdc3Version:"1.2"});return{...n,unsubscribe:()=>n.then(t=>t.unsubscribe())}}async raiseIntent(t,e,n){this.wire.recordAnalytic("fdc3-raise-intent");const i=n?{name:t,context:e,metadata:{target:n}}:{name:t,context:e};try{return await this.client.fireIntent(i)}catch(t){const e=t.message===qe.fireIntent?"ResolverUnavailable":t.message;throw new Error(e)}}async findIntent(t,e){this.wire.recordAnalytic("fdc3-find-intent");try{return await this.client.getInfoForIntent({name:t,context:e})}catch(t){const e=t.message===qe.getInfoForIntent?"ResolverUnavailable":t.message;throw new Error(e)}}async findIntentsByContext(t){this.wire.recordAnalytic("fdc3-find-intents-by-context");try{return await this.client.getInfoForIntentsByContext(t)}catch(t){const e=t.message===qe.getInfoForIntentsByContext?"ResolverUnavailable":t.message;throw new Error(e)}}async raiseIntentForContext(t,e){this.wire.recordAnalytic("fdc3-raise-intent-for-context");try{return await this.client.fireIntentForContext({...t,metadata:{target:e}})}catch(t){const e=t.message===qe.fireIntentForContext?"ResolverUnavailable":t.message;throw new Error(e)}}async getOrCreateChannel(t){return super.getOrCreateChannel(t,Ln)}getInfo(){this.wire.recordAnalytic("fdc3-get-info");return{providerVersion:this.wire.environment.getAdapterVersionSync(),provider:`openfin-${this.wire.me.uuid}`,fdc3Version:"1.2"}}}class Un extends Dn{async open(t,e){return"string"==typeof t&&console.warn("Passing a string as the app parameter is deprecated, please use an AppIdentifier ({ appId: string; instanceId?: string })."),super._open(t,e)}async findInstances(t){this.wire.recordAnalytic("fdc3-find-instances");try{return await Sn.ferryFdc3Call(this.client,"fdc3FindInstances",t)}catch(t){const e=t.message===qe.fdc3FindInstances?"ResolverUnavailable":t.message;throw new Error(e)}}async getAppMetadata(t){this.wire.recordAnalytic("fdc3-get-app-metadata");try{return await Sn.ferryFdc3Call(this.client,"fdc3GetAppMetadata",t)}catch(t){const e=t.message===qe.fdc3GetAppMetadata?"ResolverUnavailable":t.message;throw new Error(e)}}async addContextListener(t,e){this.wire.recordAnalytic("fdc3-add-context-listener");const n=t=>e=>{const{contextMetadata:n,...i}=e,r=n?[{...i},n]:[e,null];t(...r)};let i=e,r=n(i);return"function"==typeof t?(console.warn("addContextListener(handler) has been deprecated. Please use addContextListener(null, handler)"),i=t,r=n(i),this.client.addContextHandler(r)):this.client.addContextHandler(r,null===t?void 0:t)}async findIntent(t,e,n){this.wire.recordAnalytic("fdc3-find-intent");try{return await this.client.getInfoForIntent({name:t,context:e,metadata:{resultType:n}})}catch(t){const e=t.message===qe.getInfoForIntent?"ResolverUnavailable":t.message;throw new Error(e)}}async findIntentsByContext(t,e){this.wire.recordAnalytic("fdc3-find-intents-by-context");const n=e?{context:t,metadata:{resultType:e}}:t;try{return await Sn.ferryFdc3Call(this.client,"fdc3v2FindIntentsByContext",n)}catch(t){const e=t.message===qe.getInfoForIntentsByContext?"ResolverUnavailable":t.message;throw new Error(e)}}async raiseIntent(t,e,n){this.wire.recordAnalytic("fdc3-raise-intent");try{return"string"==typeof n&&console.warn("Passing a string as the app parameter is deprecated, please use an AppIdentifier ({ appId: string; instanceId?: string })."),jn(this.client,e,n,t)}catch(t){const e=t.message===qe.fireIntent?"ResolverUnavailable":t.message;throw new Error(e)}}async raiseIntentForContext(t,e){this.wire.recordAnalytic("fdc3-raise-intent-for-context");try{return"string"==typeof e&&console.warn("Passing a string as the app parameter is deprecated, please use an AppIdentifier ({ appId: string; instanceId?: string })."),jn(this.client,t,e)}catch(t){const e=t.message===qe.fireIntent?"ResolverUnavailable":t.message;throw new Error(e)}}async addIntentListener(t,e){if(this.wire.recordAnalytic("fdc3-add-intent-listener"),"string"!=typeof t)throw new Error("First argument must be an Intent name");return this.client.registerIntentHandler(async t=>{let n,i;const{context:r,metadata:s}=t,{contextMetadata:o,metadata:a,...c}=r,d=s?.intentResolutionResultId||a?.intentResolutionResultId;try{const t=a?{metadata:a,...c}:{...c};n=await e(t,o),i=n}catch(t){n=t,i={error:!0}}if(d&&this.fin.InterApplicationBus.publish(d,i).catch(()=>null),n instanceof Error)throw new Error(n.message);return n},t,{fdc3Version:"2.0"})}async getOrCreateChannel(t){return super.getOrCreateChannel(t,$n)}async createPrivateChannel(){const t=De();await Sn.ferryFdc3Call(this.client,"createPrivateChannelProvider",{channelId:t});const e=await this.fin.InterApplicationBus.Channel.connect(t),n=new Tn(e,t);return Wn(n)}async getUserChannels(){return(await this.client.getContextGroups()).map(t=>({...t,type:"user",...Fn("User")}))}async getSystemChannels(){return console.warn("This API has been deprecated. Please use fdc3.getUserChannels instead."),super.getSystemChannels()}async joinUserChannel(t){return super.joinChannel(t)}async joinChannel(t){return console.warn("This API has been deprecated. Please use fdc3.joinUserChannel instead."),super.joinChannel(t)}async getCurrentChannel(){const t=await super.getCurrentChannel();return t?{...t,type:"user",broadcast:this.broadcast.bind(this)}:null}async getInfo(){return Sn.ferryFdc3Call(this.client,"fdc3v2GetInfo",{fdc3Version:"2.0"})}}const zn=(t,e,n)=>{switch(t){case"1.2":return new Vn(()=>e,n);case"2.0":return new Un(()=>e,n);default:throw new Error(`Invalid FDC3 version provided: ${t}. Must be '1.2' or '2.0'`)}},_n=t=>new t,qn="You have attempted to use or modify InteropBroker parameters, which is not allowed. You are likely using an older InteropBroker override scheme. Please consult our Interop docs for guidance on migrating to the new override scheme.";class Jn extends l{async init(t,e=_n){this.wire.recordAnalytic("interop-init");const n=await this.wire.environment.getInteropInfo(this.wire.getFin()),i=function(t){const e=()=>{throw new Error(t)};return new Proxy({},{apply:e,construct:e,defineProperty:e,deleteProperty:e,get:e,getOwnPropertyDescriptor:e,getPrototypeOf:e,has:e,isExtensible:e,ownKeys:e,preventExtensions:e,set:e,setPrototypeOf:e})}(qn),r=(s=qn,o=structuredClone(n),new Proxy(o,{get:(...t)=>(console.warn(s),Reflect.get(...t)),set:(...t)=>(console.warn(s),Reflect.set(...t)),getOwnPropertyDescriptor:(...t)=>(console.warn(s),Reflect.getOwnPropertyDescriptor(...t)),ownKeys:(...t)=>(console.warn(s),Reflect.ownKeys(...t))}));var s,o;const a=async()=>{throw new Error(qn)},c=on.createClosedConstructor(this.wire,()=>this.fin.InterApplicationBus.Channel.create(`interop-broker-${t}`),n);let d;if(Array.isArray(e)){d=new(function(...t){return e=>t.reduceRight((t,e)=>n=>e(t(n)),t=>t)(e)}(...e)(c))(i,a,r)}else d=await e(c,i,a,r);return kn(d,n.fdc3Version),d}connectSync(t,e){return this.wire.recordAnalytic("interop-connect-sync"),new Sn(this.wire,this.wire.environment.whenReady().then(()=>this.fin.InterApplicationBus.Channel.connect(`interop-broker-${t}`,{payload:e})),zn)}}const Yn=t=>`snapshot-source-provider-${t.uuid}`;var Kn,Zn,Qn,Xn,ti,ei=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},ni=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};const ii=new Map;class ri extends l{constructor(t,e){super(t),Kn.set(this,void 0),Zn.set(this,()=>(ii.has(this.identity.uuid)||ii.set(this.identity.uuid,{eventFired:null,clientPromise:null}),ii.get(this.identity.uuid))),Qn.set(this,()=>(ni(this,Zn,"f").call(this).clientPromise||(ni(this,Zn,"f").call(this).clientPromise=ni(this,Xn,"f").call(this)),ni(this,Zn,"f").call(this).clientPromise)),Xn.set(this,async()=>{const t=Yn(this.identity);try{ni(this,Zn,"f").call(this).eventFired||await ni(this,ti,"f").call(this);const e=await this.fin.InterApplicationBus.Channel.connect(t,{wait:!1});return e.onDisconnection(()=>{ni(this,Zn,"f").call(this).clientPromise=null,ni(this,Zn,"f").call(this).eventFired=null}),e}catch(t){throw ni(this,Zn,"f").call(this).clientPromise=null,new Error("The targeted SnapshotSource is not currently initialized. Await this object's ready() method.")}}),ti.set(this,async()=>{const t=Yn(this.identity);let e,n;const i=new Promise((t,i)=>{e=t,n=i});ni(this,Zn,"f").call(this).eventFired=i;const r=async i=>{try{i.channelName===t&&(e(),await this.fin.InterApplicationBus.Channel.removeListener("connected",r))}catch(t){n(t)}};await this.fin.InterApplicationBus.Channel.on("connected",r)}),ei(this,Kn,e,"f")}get identity(){return ni(this,Kn,"f")}async ready(){this.wire.recordAnalytic("snapshot-source-ready");try{await ni(this,Qn,"f").call(this)}catch(t){await ni(this,Zn,"f").call(this).eventFired}}async getSnapshot(){this.wire.recordAnalytic("snapshot-source-get-snapshot");const t=await ni(this,Qn,"f").call(this),e=await t.dispatch("get-snapshot");return(await e).snapshot}async applySnapshot(t){this.wire.recordAnalytic("snapshot-source-apply-snapshot");return(await ni(this,Qn,"f").call(this)).dispatch("apply-snapshot",{snapshot:t})}}Kn=new WeakMap,Zn=new WeakMap,Qn=new WeakMap,Xn=new WeakMap,ti=new WeakMap;class si extends l{async init(t){if(this.wire.recordAnalytic("snapshot-source-init"),"object"!=typeof t||"function"!=typeof t.getSnapshot||"function"!=typeof t.applySnapshot)throw new Error("you must pass in a valid SnapshotProvider");const e=await this.fin.InterApplicationBus.Channel.create(Yn(this.fin.me));e.register("get-snapshot",async()=>({snapshot:await t.getSnapshot()})),e.register("apply-snapshot",({snapshot:e})=>t.applySnapshot(e))}wrapSync(t){return this.wire.recordAnalytic("snapshot-source-wrap-sync"),new ri(this.wire,t)}async wrap(t){return this.wire.recordAnalytic("snapshot-source-wrap"),this.wrapSync(t)}}var oi,ai,ci,di,hi=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},li=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class pi{constructor(t,e){oi.set(this,void 0),ai.set(this,void 0),ci.set(this,void 0),di.set(this,new A(async()=>(await li(this,oi,"f").registerMessageHandler(t=>{if("notification-created"===t.action&&t.payload.managerId===li(this,ci,"f")){const{notificationId:e,properties:n,documentUrl:i,notificationIcon:r,badge:s,image:o}=t.payload;try{li(this,ai,"f")?.call(this,{properties:n,images:{image:o,icon:r,badge:s},url:i,notificationId:e})}catch(t){console.error("Failed to handle notification",t)}return!0}return!1}),!0))),this.setNotificationHandler=async t=>{await li(this,di,"f").getValue(),hi(this,ai,t,"f")},this.destroy=async()=>{await li(this,oi,"f").sendAction("destroy-notification-manager",{managerId:li(this,ci,"f")})},this.dispatch=async t=>{const{notificationId:e,type:n}=t;await li(this,oi,"f").sendAction("dispatch-notification-event",{notificationId:e,type:n})},hi(this,oi,t,"f"),hi(this,ci,e,"f")}}oi=new WeakMap,ai=new WeakMap,ci=new WeakMap,di=new WeakMap;class ui extends l{constructor(){super(...arguments),this.init=async()=>{const{payload:{data:{managerId:t}}}=await this.wire.sendAction("init-notification-manager");return new pi(this.wire,t)}}}var wi,yi,fi,gi=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},mi=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class vi{constructor(t){wi.set(this,void 0),yi.set(this,new Set),fi.set(this,null),this.get=()=>mi(this,wi,"f"),this.set=t=>{if(mi(this,wi,"f")!==t){gi(this,wi,t,"f");for(const t of[...mi(this,yi,"f")])try{t()}catch(t){setTimeout(()=>{throw t},0)}}},this.subscribe=t=>(mi(this,yi,"f").add(t),()=>{mi(this,yi,"f").delete(t)}),gi(this,wi,t,"f")}get readonly(){return mi(this,fi,"f")||gi(this,fi,{get:this.get,subscribe:this.subscribe},"f"),mi(this,fi,"f")}}wi=new WeakMap,yi=new WeakMap,fi=new WeakMap;var Ci,Ii,bi=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},xi=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class Ai{constructor(t){Ci.set(this,void 0),Ii.set(this,new vi([])),bi(this,Ci,t,"f")}get state(){return xi(this,Ii,"f").readonly}static activate(t){xi(t,Ci,"f").registerMessageHandler(e=>"chrome-browser-actions-update"===e?.action&&(xi(t,Ii,"f").set(e?.payload?.actions??[]),!0))}async getExtensionActions(){return(await xi(this,Ci,"f").sendAction("chrome-browser-get-extension-actions",{})).payload.data.actions}async invokeExtensionAction(t){await xi(this,Ci,"f").sendAction("chrome-browser-invoke-extension-action",t)}async hideActiveExtensionPopup(){await xi(this,Ci,"f").sendAction("chrome-browser-hide-active-extension-popup",{})}}Ci=new WeakMap,Ii=new WeakMap;class Ei{constructor(t,e){this.Actions=new Ai(t),e&&Ai.activate(this.Actions)}}class Pi extends t{constructor(t){super(),this.wire=t,this.System=new V(t),this.Window=new $(t),this.Application=new T(t),this.InterApplicationBus=new Qt(t),this.Clipboard=new Xt(t),this.ExternalApplication=new ee(t),this.Frame=new ie(t),this.GlobalHotkey=new re(t),this.Platform=new Ne(t,this.InterApplicationBus.Channel),this.View=new x(t),this.Interop=new Jn(t),this.SnapshotSource=new si(t),this.NotificationManager=new ui(t),this.ChromeBrowser=new Ei(t,"window"===t.me.entityType),t.registerFin(this),this.me=function(t){const{uuid:e,name:n,entityType:i}=t.me,r={setContext(){throw new Error(He)},addContextHandler(){throw new Error(He)},getContextGroups(){throw new Error(He)},joinContextGroup(){throw new Error(He)},removeFromContextGroup(){throw new Error(He)},getAllClientsInContextGroup(){throw new Error(He)},getInfoForContextGroup(){throw new Error(He)}},s="Interop API has not been instantiated. Either connection has failed or you have not declared interop in your config.",o={setContext(){throw new Error(s)},addContextHandler(){throw new Error(s)},getContextGroups(){throw new Error(s)},joinContextGroup(){throw new Error(s)},removeFromContextGroup(){throw new Error(s)},getAllClientsInContextGroup(){throw new Error(s)},getInfoForContextGroup(){throw new Error(s)}},a={eventNames:()=>{throw new Error(He)},emit:()=>{throw new Error(He)},listeners:()=>{throw new Error(He)},listenerCount:()=>{throw new Error(He)},on:()=>{throw new Error(He)},addListener:()=>{throw new Error(He)},once:()=>{throw new Error(He)},prependListener:()=>{throw new Error(He)},prependOnceListener:()=>{throw new Error(He)},removeListener:()=>{throw new Error(He)},removeAllListeners:()=>{throw new Error(He)}};switch(i){case"view":return Object.assign(new S(t,{uuid:e,name:n}),Be(i,e,n),{interop:o,isOpenFin:!0});case"window":return Object.assign(new L(t,{uuid:e,name:n}),Be(i,e,n),{interop:o,isOpenFin:!0});case"iframe":return Object.assign(new ne(t,{uuid:e,name:n}),Be(i,e,n),{interop:o,isOpenFin:!0});case"external connection":return Object.assign(new te(t,{uuid:e}),Be(i,e,n),{interop:o,isOpenFin:!1});default:return{...Be(i,e,n),...a,interop:r,isOpenFin:!1}}}(t),t.on("disconnected",()=>{this.emit("disconnected")})}}function Mi(t){return ki(t)&&"string"==typeof t.address}function Si(t){return Mi(t)&&"string"==typeof t.token}function ki(t){return"string"==typeof t.uuid}class Ti{constructor(){this.storage=new Map}hashKeys(t){return t.map(Li).join("/")}getOrCreate(e){const n=this.hashKeys(e);return this.storage.has(n)||this.storage.set(n,new t),this.storage.get(n)}has(t){return this.storage.has(this.hashKeys(t))}delete(t){const e=this.hashKeys(t);return this.storage.delete(e)}}function Li(t){return btoa(t)}class $i extends Ti{constructor(){super(...arguments),this.dispatchEvent=t=>{if(function(t){return"process-desktop-event"===t.action}(t)){const{payload:e}=t,n=function(t){const{topic:e}=t;if("frame"===e||"window"===e||"view"===e){const{uuid:n,name:i}=t;return[e,n,i]}if("application"===e){const{uuid:n}=t;return[e,n]}return[e]}(e);if(this.has(n))return this.getOrCreate(n).emit(e.type,e),!0}return!1}}}var Fi,Gi,Ri,Oi,Wi,ji,Ni,Hi=function(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n},Bi=function(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)};class Di extends t{constructor(t,e,n){super(),Fi.add(this),this.wireListeners=new Map,this.topicRefMap=new Map,this.eventAggregator=new $i,this.messageHandlers=[this.eventAggregator.dispatchEvent],Gi.set(this,void 0),Ri.set(this,!0),Oi.set(this,new Map),Wi.set(this,void 0),ji.set(this,void 0),this.connectSync=()=>{Bi(this,Gi,"f").connectSync()},this.getPort=()=>Bi(this,Gi,"f").getPort(),Hi(this,Gi,t(this.onmessage.bind(this)),"f"),this.environment=e,Hi(this,Ri,!1!==n.apiDiagnostics,"f"),this.sendRaw=Bi(this,Gi,"f").send.bind(Bi(this,Gi,"f")),this.registerMessageHandler(this.handleMessage.bind(this)),Bi(this,Gi,"f").on("disconnected",()=>{for(const[,{handleNack:t}]of this.wireListeners)t({reason:"Remote connection has closed"});this.wireListeners.clear(),clearTimeout(Bi(this,Wi,"f")),Hi(this,Wi,void 0,"f"),Bi(this,Oi,"f").clear(),this.emit("disconnected")});const{uuid:i,name:r}=n,s=this.environment.getCurrentEntityType();this.me=Be(s,i,r),this.environment.onBFCacheRestore(async()=>{await this.sendAction("write-to-log",{level:"verbose",message:`Page restored from the back/forward cache for ${i}/${r}`,target:{}})})}getFin(){if(!Bi(this,ji,"f"))throw new Error("No Fin object registered for this transport");return Bi(this,ji,"f")}registerFin(t){if(Bi(this,ji,"f"))throw new Error("Fin object has already been registered for this transport");Hi(this,ji,t,"f")}recordAnalytic(t){if(Bi(this,Ri,"f")&&(Bi(this,Oi,"f").set(t,(Bi(this,Oi,"f").get(t)??0)+1),void 0===Bi(this,Wi,"f"))){const t=setTimeout(()=>Bi(this,Fi,"m",Ni).call(this),3e4);"object"==typeof t&&null!==t&&t.unref?.(),Hi(this,Wi,t,"f")}}shutdown(){return Bi(this,Gi,"f").shutdown()}async connect(t){if(function(t){return"object"==typeof t.receiver&&Si({...t,address:""})}(t))return await Bi(this,Gi,"f").connect(t.receiver),this.authorize(t);if(Si(t))return this.connectRemote(t);if(Mi(t))return this.connectByPort(t);if(function(t){return ki(t)&&function(t){return t.runtime&&"string"==typeof t.runtime.version}(t)}(t)){const e=await this.environment.retrievePort(t);return this.connectByPort({...t,address:`ws://localhost:${e}`})}}async connectRemote(t){return await Bi(this,Gi,"f").connect(new(this.environment.getWsConstructor())(t.address)),this.authorize(t)}async connectByPort(t){const{address:e,uuid:n}=t,i={...t,type:"file-token"},r=Bi(this,Gi,"f");await r.connect(new(this.environment.getWsConstructor())(t.address));const s=await this.sendAction("request-external-authorization",{uuid:n,type:"file-token"},!0);if("external-authorization-response"!==s.action)throw new y(s.action);return await this.environment.writeToken(s.payload.file,s.payload.token),this.authorize(i)}async authorize(t){const e=await this.sendAction("request-authorization",t,!0);if("authorization-response"!==e.action)throw new y(e.action);if(!0!==e.payload.success)throw new C(e.payload)}sendAction(t,e={},n=!1){let i=()=>{};const r=C.getCallSite(1),s=this.environment.getNextMessageId(),o=new Promise((o,a)=>{i=a;const c={action:t,payload:e,messageId:s},d=Bi(this,Gi,"f");return this.addWireListener(s,o,t=>this.nackHandler(t,a,r),n),d.send(c).catch(a)});return Object.assign(o,{cancel:i,messageId:s})}nackHandler(t,e,n){e("string"==typeof t?t:new C(t,n))}ferryAction(t){return new Promise((e,n)=>{const i=this.environment.getNextMessageId();t.messageId=i;const r=t=>{e(t.payload)};return Bi(this,Gi,"f").send(t).then(()=>this.addWireListener(i,r,t=>this.nackHandler(t,n),!1)).catch(n)})}registerMessageHandler(t){this.messageHandlers.push(t)}addWireListener(t,e,n,i){i?this.uncorrelatedListener=e:this.wireListeners.has(t)?n({reason:"Duplicate handler id",error:ht(new f(String(t)))}):this.wireListeners.set(t,{resolve:e,handleNack:n})}onmessage(t){for(const e of this.messageHandlers)e.call(null,t)}handleMessage(t){const e=t.correlationId||NaN;if("correlationId"in t){if(!this.wireListeners.has(e))return!1;{const{resolve:n,handleNack:i}=this.wireListeners.get(e);"ack"!==t.action?i({reason:"Did not receive ack action",error:ht(new g(t.action))}):"payload"in t?t.payload.success?n.call(null,t):i(t.payload):"string"==typeof t.reason?i(t):(console.warn("Received invalid response from core",t),i({reason:"invalid response shape",error:ht(new Error("Invalid response shape"))})),this.wireListeners.delete(e)}}else this.uncorrelatedListener&&this.uncorrelatedListener.call(null,t),this.uncorrelatedListener=()=>{};return!0}}Gi=new WeakMap,Ri=new WeakMap,Oi=new WeakMap,Wi=new WeakMap,ji=new WeakMap,Fi=new WeakSet,Ni=function(){if(Hi(this,Wi,void 0,"f"),0===Bi(this,Oi,"f").size)return;const t=Object.fromEntries(Bi(this,Oi,"f"));Bi(this,Oi,"f").clear(),this.sendAction("send-analytics-batch",{counts:t}).catch(()=>{})};const Vi=new Map([["debug",0],["info",1],["warn",2],["error",3],["none",4]]),Ui=t=>"string"==typeof t?t:t instanceof Error?t.stack||t.message:JSON.stringify(t);class zi{static setGlobalLogLevel(t){zi.LOG_LEVEL=t??"error"}static setCustomLogger(t){zi.customLogger=t}constructor(...t){this.scopes=t}log(t,...e){const n=Vi.get(t)??3;if((Vi.get(zi.LOG_LEVEL)??3)<=n){const r=[`[${(new Date).toISOString()}]`,...(i=this.scopes,i.map(t=>`[${t}]`)),...e];if(zi.customLogger){const e=r.map(Ui).join(" ");zi.customLogger[t](e)}else 1===n?console.log(...r):console[t](...r)}var i}warn(...t){this.log("warn",...t)}error(...t){this.log("error",...t)}info(...t){this.log("info",...t)}debug(...t){this.log("debug",...t)}static getLogger(...t){return new zi(...t)}getLogger(...t){return new zi(...this.scopes,...t)}}zi.LOG_LEVEL="error";const _i=zi.getLogger("@openfin/core-web/client"),qi=_i.getLogger("data-channel"),Ji=t=>`data-channel-${t.me.uuid}`,Yi=async(t,e)=>{const n=async n=>t.dispatch("page-title-updated",{data:{identity:e,title:n}}).catch(t=>{qi.warn("Failed to dispatch title change",t)});document.title&&await n(document.title),s(document.head,n);const i=async n=>t.dispatch("page-favicon-updated",{data:{identity:e,favicon:n}}).catch(t=>{qi.warn("Failed to dispatch favicon change",t)}),r=document.querySelector('link[rel~="icon"]')?.href;r&&await i(r),o(document.head,t=>{i(t)})};function Ki(t,e){if(!function(t){return"string"==typeof t}(t))throw new Error(`Property ${e} has invalid type. Expected string, got ${typeof t}.`)}const Zi="web-broker-ports-ready",Qi=_i.getLogger("get-web-interop-ports");function Xi(t,e,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(t):i?i.value:e.get(t)}function tr(t,e,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(t,n):r?r.value=n:e.set(t,n),n}var er,nr,ir;"function"==typeof SuppressedError&&SuppressedError;class rr extends t{constructor(t,e){super(),er.set(this,void 0),nr.set(this,void 0),ir.set(this,!1),this.connectSync=()=>{Xi(this,ir,"f")||(Xi(this,nr,"f").addEventListener("message",t=>{t.data?.topic?.startsWith("wire-message")&&t.data.message&&Xi(this,er,"f").call(this,{...JSON.parse(t.data.message),ports:t.ports})}),Xi(this,nr,"f").start())},this.connect=async()=>{this.connectSync()},this.send=t=>(Xi(this,nr,"f").postMessage({topic:"wire-message",message:JSON.stringify(t)}),Promise.resolve()),this.shutdown=async()=>{Xi(this,nr,"f").close()},tr(this,er,t,"f"),tr(this,nr,e,"f")}getPort(){return Xi(this,nr,"f")}}er=new WeakMap,nr=new WeakMap,ir=new WeakMap;class sr{async getViewWindowIdentity(t,e){const{identity:n}=await t.View.wrapSync(e).getCurrentWindow();return n}async getInteropInfo(t){const e=await t.Application.getCurrentSync().getInfo().catch(()=>null),n=e?.initialOptions?.interopBrokerConfiguration??{};return{fdc3Version:e?function({manifest:t,initialOptions:e}){const n=t?.platform?.defaultViewOptions?.fdc3InteropApi??e.defaultViewOptions?.fdc3InteropApi;return["1.2","2.0"].includes(n??"")?n:void 0}(e):void 0,...n,fdc3Info:{providerVersion:await t.System.getVersion(),provider:"OpenFin"}}}}class or extends sr{constructor(){super(...arguments),this.type="other",this.getRandomId=()=>{const t=new Uint32Array(1);return window.crypto.getRandomValues(t)[0].toString(32)}}getAdapterVersionSync(){return""}observeBounds(t,e){throw new Error("Method not implemented.")}onBFCacheRestore(t){return()=>{}}layoutAllowedInContext(t){return!1}initLayoutManager(t,e,n){throw new Error("Method not implemented.")}applyLayoutSnapshot(t,e,n){throw new Error("Method not implemented.")}createLayout(t,e){throw new Error("Method not implemented.")}destroyLayout(t,e){throw new Error("Method not implemented.")}resolveLayout(t,e){throw new Error("Method not implemented.")}initPlatform(...t){throw new Error("Method not implemented.")}writeToken(t,e){return Promise.resolve("")}retrievePort(t){throw new Error("Method not implemented.")}getNextMessageId(){return this.getRandomId()}createChildContent(t){throw new Error("Method not implemented.")}getWebWindow(t){throw new Error("Method not implemented.")}getCurrentEntityIdentity(){throw new Error("Method not implemented.")}getCurrentEntityType(){return"external connection"}raiseEvent(t,e){throw new Error("Method not implemented.")}getUrl(){return location.href}getDefaultChannelOptions(){return{create:{},connect:{}}}getRtcPeer(){return new RTCPeerConnection}getWsConstructor(){return WebSocket}whenReady(){return Promise.resolve()}}const ar=t=>"platform"in t&&void 0!==t.platform;var cr,dr;class hr extends or{constructor(t){super(),this.connectConfig=t,cr.set(this,void 0),dr.set(this,new A(async()=>import("./main-7f56b5d7.js"))),ar(t)&&this.validatePlatformOptions(t)}getAdapterVersionSync(){return"0.47.1"}validatePlatformOptions({platform:t}){if(!("layoutSnapshot"in t))throw new Error("Platform options are missing layoutSnapshot. Please provide a layoutSnapshot in the platform options.");if("windows"in t||"windows"in t.layoutSnapshot)throw new Error("It appears you tried to call connect() with a snapshot object from an OpenFin desktop environment. Note that connect() expects to be called with a platform property with this structure: { platform: { layoutSnapshot } }. To get a layoutSnapshot of the expected structure, use fin.Platform.Layout.getCurrentLayoutManagerSync().getLayoutSnapshot() in v34+ in your desktop environment.");const{layouts:e}=t.layoutSnapshot;Object.entries(e).map(([t,e])=>{if("object"!=typeof e||null===e)throw new Error(`Invalid layout detected: layoutSnapshot.layouts.${t} must be an object.`);if(!("content"in e))throw new Error(`Invalid layout detected: layoutSnapshot.layouts.${t} must contain a 'content' property.`)})}async getInteropInfo(t){return{...{contextGroups:void 0,logging:{beforeAction:{enabled:!1},afterAction:{enabled:!1}}},fdc3Version:void 0,fdc3Info:{providerVersion:"0.47.1",provider:"OpenFin Web"}}}layoutAllowedInContext(t){return!0}async initLayoutManager(t,e,n){if(Xi(this,cr,"f"))throw new Error("Layout already initialized.");if(!ar(this.connectConfig))throw new Error("Platform options are missing from connection config.");const{WebLayoutEntryPoint:i}=await Xi(this,dr,"f").getValue();return tr(this,cr,new i(this.connectConfig),"f"),await Xi(this,cr,"f").initLayoutManager(t,e,n)}async applyLayoutSnapshot(t,e,n){Xi(this,cr,"f")?.applyLayoutSnapshot(t,e,n)}async createLayout(t,e){return Xi(this,cr,"f")?.createLayout(t,e)}async destroyLayout(t,e){return Xi(this,cr,"f")?.destroyLayout(t,e)}async getViewWindowIdentity(t,e){return Promise.resolve({uuid:e.uuid,name:e.uuid})}}cr=new WeakMap,dr=new WeakMap;const lr=()=>{const t=((t,e)=>{const n=new RegExp(`^${e}<(?<meta>.*)>$`).exec(t)?.groups?.meta;if(n)try{return JSON.parse(atob(n))}catch(t){throw new Error(`Failed to decode JSON from ${n}.`)}})(window.name,"of-frame");if(t)try{const{name:e,uuid:n,brokerUrl:i,providerId:r,contextGroup:s}=t;return Ki(i,"brokerUrl"),Ki(n,"uuid"),Ki(e,"name"),{identity:{name:e,uuid:n},brokerUrl:i,interopConfig:{providerId:r,currentContextGroup:s},isOfView:!0}}catch(t){throw new Error(`Unexpected error occurred when inferring platform information: ${t.stack}`)}},pr=()=>{const t=n();return{uuid:t,name:t}},ur=async t=>{if("enabled"===t.connectionInheritance){const e=await(async t=>{const e=lr();if(e){const{validateOptions:n=()=>!0}=t,{identity:i,...r}=e;if(!await n(r))throw new Error("Parent options were rejected by validateOptions.");return e}})(t);if(e)return e}if(!t.options){const e="enabled"===t.connectionInheritance?"Broker URL was not specified nor provided by a platform container.":"Connection inheritance is disabled but no options were provided.";throw new Error(e)}return{...t.options,identity:pr(),isOfView:!1}},wr=async t=>{try{zi.setGlobalLogLevel(t.logLevel),zi.setCustomLogger(t.logger),_i.info("Establishing connection",t);const{brokerUrl:e,identity:n,timeout:s,interopConfig:o,isOfView:a}=await ur(t),{workerPort:c,iframeBrokerPort:d}=await(async(t,e,n)=>{const{origin:r}=new URL(t),s=document.createElement("IFRAME");let o;s.style.display="none";try{return await new Promise((a,c)=>{const d=t=>{if(t.source===s.contentWindow&&t.data?.topic===`ack-${Zi}`){if(t.origin!==r)c(new Error(`Broker redirected to unexpected origin ${t.origin}, expected ${r}.`));else if(t.data.success){const[e,n]=t.ports;a({iframeBrokerPort:e,workerPort:n})}else c(new C(t.data));window.removeEventListener("message",d),clearTimeout(o)}};window.addEventListener("message",d),Qi.info(`Connecting to broker ${t}`),s.setAttribute("src",t),s.setAttribute("name",i(e,"of-broker")),document.body.appendChild(s),Qi.info("Iframe loaded, awaiting init message from iframe"),n&&(o=setTimeout(()=>{window.removeEventListener("message",d),document.body.removeChild(s),c(new Error("Worker did not initialize in time"))},n))})}catch(t){throw new Error(`Failed to initialise Fin Web Client. ${t.message}`,{cause:t})}})(e,n,s);_i.info("Successfully established connection to shared worker");const h={entityType:"external connection",...n};c.start(),d.start();const l=((t,e,n)=>{const i=new hr(t),r=new Di(t=>new rr(t,e),i,n);return r.connectSync(),new Pi(r)})(t,c,h);return a&&window.top&&!r(window,window.top)&&(t=>{const e={uuid:t.me.uuid,name:t.me.name};qi.debug("Data channel connecting..."),t.InterApplicationBus.Channel.connect(Ji(t)).then(async t=>{qi.debug("Data channel connected"),await Yi(t,e)}).catch(t=>{qi.warn("Failed to connect to data channel, some features may not work like title updates",t)})})(l),o?.providerId&&(l.me.interop=l.Interop.connectSync(o.providerId),o?.currentContextGroup&&l.me.interop.joinContextGroup(o.currentContextGroup).catch(t=>{_i.warn(`Error joining specified context group: ${o?.currentContextGroup}, continuing`,t)})),{...l,me:{...l.me,identity:{uuid:l.me.uuid,name:l.me.name}}}}catch(t){throw new Error(`An error occured during web-interop connection: ${t.message}`)}};export{A as L,Xi as _,Ee as a,tr as b,o as c,_i as d,i as e,zi as f,s as g,Ji as h,r as i,wr as j,we as r};
|