@interopio/browser-platform 3.0.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.
Files changed (97) hide show
  1. package/browser.platform.d.ts +455 -0
  2. package/changelog.md +69 -0
  3. package/dist/browser.platform.es.js +46074 -0
  4. package/dist/browser.platform.es.js.map +1 -0
  5. package/dist/browser.platform.umd.js +46082 -0
  6. package/dist/browser.platform.umd.js.map +1 -0
  7. package/license.md +21 -0
  8. package/package.json +78 -0
  9. package/readme.md +9 -0
  10. package/rollup.config.js +45 -0
  11. package/src/common/constants.ts +46 -0
  12. package/src/common/defaultConfig.ts +56 -0
  13. package/src/common/gateway.d.ts +32 -0
  14. package/src/common/types.ts +222 -0
  15. package/src/connection/gateway.ts +132 -0
  16. package/src/connection/no-gateway.ts +1 -0
  17. package/src/connection/portsBridge.ts +441 -0
  18. package/src/connection/preferred.ts +247 -0
  19. package/src/controllers/domains.ts +156 -0
  20. package/src/controllers/glue.ts +604 -0
  21. package/src/controllers/interception.ts +53 -0
  22. package/src/controllers/license.ts +50 -0
  23. package/src/controllers/main.ts +256 -0
  24. package/src/controllers/plugins.ts +121 -0
  25. package/src/controllers/serviceWorker.ts +193 -0
  26. package/src/controllers/state.ts +84 -0
  27. package/src/controllers/system.ts +99 -0
  28. package/src/controllers/transactions.ts +80 -0
  29. package/src/factory.ts +40 -0
  30. package/src/fallbacks/browser.ts +47 -0
  31. package/src/fallbacks/dekstop.ts +21 -0
  32. package/src/index.ts +18 -0
  33. package/src/libs/applications/appStore/directory.ts +235 -0
  34. package/src/libs/applications/appStore/remoteWatcher.ts +112 -0
  35. package/src/libs/applications/controller.ts +469 -0
  36. package/src/libs/applications/decoders.ts +98 -0
  37. package/src/libs/applications/defaults.ts +6 -0
  38. package/src/libs/applications/types.ts +98 -0
  39. package/src/libs/channels/controller.ts +109 -0
  40. package/src/libs/channels/decoders.ts +19 -0
  41. package/src/libs/extension/controller.ts +120 -0
  42. package/src/libs/extension/decoders.ts +18 -0
  43. package/src/libs/extension/types.ts +11 -0
  44. package/src/libs/intents/constants.ts +9 -0
  45. package/src/libs/intents/controller.ts +500 -0
  46. package/src/libs/intents/decoders.ts +96 -0
  47. package/src/libs/intents/resolverHelper.ts +264 -0
  48. package/src/libs/intents/types.ts +119 -0
  49. package/src/libs/layouts/constants.ts +3 -0
  50. package/src/libs/layouts/controller.ts +476 -0
  51. package/src/libs/layouts/decoders.ts +132 -0
  52. package/src/libs/layouts/global/builder.ts +400 -0
  53. package/src/libs/layouts/global/resetter.ts +116 -0
  54. package/src/libs/layouts/global/restorer.ts +217 -0
  55. package/src/libs/layouts/global/validator.ts +169 -0
  56. package/src/libs/layouts/idbStore.ts +63 -0
  57. package/src/libs/layouts/types.ts +133 -0
  58. package/src/libs/manager/controller.ts +175 -0
  59. package/src/libs/manager/decoders.ts +6 -0
  60. package/src/libs/manager/defaults.ts +5 -0
  61. package/src/libs/manager/identity.ts +92 -0
  62. package/src/libs/manager/session.ts +195 -0
  63. package/src/libs/manager/types.ts +51 -0
  64. package/src/libs/notifications/controller.ts +447 -0
  65. package/src/libs/notifications/decoders.ts +166 -0
  66. package/src/libs/notifications/types.ts +49 -0
  67. package/src/libs/notifications/utils.ts +7 -0
  68. package/src/libs/search/controller.ts +232 -0
  69. package/src/libs/search/decoders.ts +6 -0
  70. package/src/libs/search/repositories/applications.ts +62 -0
  71. package/src/libs/search/repositories/layouts.ts +48 -0
  72. package/src/libs/search/repositories/workspaces.ts +47 -0
  73. package/src/libs/search/types.ts +9 -0
  74. package/src/libs/themes/constants.ts +9 -0
  75. package/src/libs/themes/controller.ts +153 -0
  76. package/src/libs/themes/decoders.ts +28 -0
  77. package/src/libs/themes/types.ts +28 -0
  78. package/src/libs/windows/controller.ts +498 -0
  79. package/src/libs/windows/decoders.ts +64 -0
  80. package/src/libs/windows/types.ts +59 -0
  81. package/src/libs/workspaces/controller.ts +922 -0
  82. package/src/libs/workspaces/decoders.ts +868 -0
  83. package/src/libs/workspaces/defaultConfig.ts +11 -0
  84. package/src/libs/workspaces/frames.ts +239 -0
  85. package/src/libs/workspaces/hibernationWatcher.ts +231 -0
  86. package/src/libs/workspaces/types.ts +506 -0
  87. package/src/platform.ts +156 -0
  88. package/src/shared/decoders.ts +479 -0
  89. package/src/shared/fetchTimeout.ts +25 -0
  90. package/src/shared/ioc.ts +580 -0
  91. package/src/shared/logger.ts +19 -0
  92. package/src/shared/promisePlus.ts +62 -0
  93. package/src/shared/sequelizer.ts +48 -0
  94. package/src/shared/utils.ts +86 -0
  95. package/src/storage/local.ts +111 -0
  96. package/src/storage/session.ts +436 -0
  97. package/tsconfig.json +16 -0
@@ -0,0 +1,84 @@
1
+ import { SessionStorageController } from "../storage/session";
2
+ import {
3
+ default as CallbackRegistryFactory,
4
+ CallbackRegistry,
5
+ UnsubscribeFunction,
6
+ } from "callback-registry";
7
+ import { IOConnectCore } from "@interopio/core";
8
+ import logger from "../shared/logger";
9
+
10
+ export class WindowsStateController {
11
+ private readonly registry: CallbackRegistry = CallbackRegistryFactory();
12
+ private readonly checkIntervalMs = 500;
13
+ private childrenToCheck: Array<{ window: Window; windowId: string }> = [];
14
+ private checkerCancelled = false;
15
+ private currentTimeout: NodeJS.Timeout | undefined;
16
+
17
+ constructor(private readonly sessionStorage: SessionStorageController) {}
18
+
19
+ private get logger(): IOConnectCore.Logger.API | undefined {
20
+ return logger.get("state.controller");
21
+ }
22
+
23
+ public start(): void {
24
+ this.checkerCancelled = false;
25
+
26
+ const nonGlueWindows = this.sessionStorage.getAllNonGlue();
27
+
28
+ nonGlueWindows.forEach((w) => {
29
+ this.logger?.trace(`detected non glue window with id ${w.windowId} from previous session, attempting reference refresh`);
30
+ const nativeWindow = window.open(undefined, w.windowId);
31
+ if (nativeWindow) {
32
+ this.childrenToCheck.push({ window: nativeWindow, windowId: w.windowId });
33
+ }
34
+ });
35
+
36
+ this.checkWindows();
37
+ }
38
+
39
+ public add(child: Window, windowId: string): void {
40
+ this.logger?.trace(`adding window id: ${windowId} to non glue state checking`);
41
+ const saved = this.sessionStorage.saveNonGlue({ windowId });
42
+
43
+ if (saved) {
44
+ this.childrenToCheck.push({ window: child, windowId });
45
+ }
46
+
47
+ }
48
+
49
+ public remove(windowId: string): void {
50
+ this.logger?.trace(`removing window id: ${windowId} from non glue state checking`);
51
+ this.sessionStorage.removeNonGlue({ windowId });
52
+ this.childrenToCheck = this.childrenToCheck.filter((w) => w.windowId !== windowId);
53
+ }
54
+
55
+ public cancel(): void {
56
+ if (this.currentTimeout) {
57
+ clearTimeout(this.currentTimeout);
58
+ }
59
+ this.checkerCancelled = true;
60
+
61
+ this.registry.clear();
62
+ }
63
+
64
+ public onWindowDisappeared(cb: (windowId: string) => void | Promise<void>): UnsubscribeFunction {
65
+ return this.registry.add("window-disappear", cb);
66
+ }
67
+
68
+ private checkWindows(): void {
69
+ if (this.checkerCancelled) {
70
+ return;
71
+ }
72
+
73
+ this.childrenToCheck.forEach((child) => {
74
+ if (!child.window || child.window.closed) {
75
+ this.logger?.trace(`non glue window ${child.windowId} has disappeared, removing from collections and announcing.`);
76
+ this.remove(child.windowId);
77
+ this.registry.execute("window-disappear", child.windowId);
78
+ return;
79
+ }
80
+ });
81
+
82
+ this.currentTimeout = setTimeout(this.checkWindows.bind(this), this.checkIntervalMs);
83
+ }
84
+ }
@@ -0,0 +1,99 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { IOConnectCore } from "@interopio/core";
3
+ import { BridgeOperation, InternalPlatformConfig, LibController, OperationCheckConfig, OperationCheckResult, SystemOperationTypes } from "../common/types";
4
+ import { anyDecoder, operationCheckConfigDecoder, operationCheckResultDecoder, systemOperationTypesDecoder } from "../shared/decoders";
5
+ import logger from "../shared/logger";
6
+ import { SessionStorageController } from "../storage/session";
7
+ import { version } from "../../package.json";
8
+
9
+ export class SystemController implements LibController {
10
+
11
+ private environment: any;
12
+ private base: any = {};
13
+ private started = false;
14
+
15
+ private platformOperations = [
16
+ "cleanupClientsOnWorkspaceFrameUnregister"
17
+ ];
18
+
19
+ private operations: { [key in SystemOperationTypes]: BridgeOperation } = {
20
+ getEnvironment: { name: "getEnvironment", resultDecoder: anyDecoder, execute: this.handleGetEnvironment.bind(this) },
21
+ getBase: { name: "getBase", resultDecoder: anyDecoder, execute: this.handleGetBase.bind(this) },
22
+ operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder, execute: this.handleOperationCheck.bind(this) }
23
+ };
24
+
25
+ constructor(private readonly session: SessionStorageController) { }
26
+
27
+ private get logger(): IOConnectCore.Logger.API | undefined {
28
+ return logger.get("applications.controller");
29
+ }
30
+
31
+ public async start(config: InternalPlatformConfig): Promise<void> {
32
+ this.environment = config.environment;
33
+ this.base = {
34
+ workspaces: {
35
+ frameCache: config.workspacesFrameCache
36
+ },
37
+ workspacesFrameCache: config.workspacesFrameCache,
38
+ communicationId: this.session.getSystemSettings()?.systemInstanceId,
39
+ platformVersion: version
40
+ };
41
+ }
42
+
43
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
44
+ public async handleControl(args: any): Promise<any> {
45
+ if (!this.started) {
46
+ new Error("Cannot handle this system control message, because the controller has not been started");
47
+ }
48
+
49
+ const applicationData = args.data;
50
+
51
+ const commandId = args.commandId;
52
+
53
+ const operationValidation = systemOperationTypesDecoder.run(args.operation);
54
+
55
+ if (!operationValidation.ok) {
56
+ throw new Error(`This system request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(operationValidation.error)}`);
57
+ }
58
+
59
+ const operationName: SystemOperationTypes = operationValidation.result;
60
+
61
+ const incomingValidation = this.operations[operationName].dataDecoder?.run(applicationData);
62
+
63
+ if (incomingValidation && !incomingValidation.ok) {
64
+ throw new Error(`System request for ${operationName} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(incomingValidation.error)}`);
65
+ }
66
+
67
+ this.logger?.debug(`[${commandId}] ${operationName} command is valid with data: ${JSON.stringify(applicationData)}`);
68
+
69
+ const result = await this.operations[operationName].execute(applicationData, commandId);
70
+
71
+ const resultValidation = this.operations[operationName].resultDecoder?.run(result);
72
+
73
+ if (resultValidation && !resultValidation.ok) {
74
+ throw new Error(`System request for ${operationName} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(resultValidation.error)}`);
75
+ }
76
+
77
+ this.logger?.trace(`[${commandId}] ${operationName} command was executed successfully`);
78
+
79
+ return result;
80
+ }
81
+
82
+ private async handleOperationCheck(config: OperationCheckConfig): Promise<OperationCheckResult> {
83
+ const operations = Object.keys(this.operations);
84
+
85
+ const isSupportedByController = operations.some((operation) => operation.toLowerCase() === config.operation.toLowerCase());
86
+
87
+ const isSupportedByPlatform = this.platformOperations.some((operation) => operation.toLowerCase() === config.operation.toLowerCase());
88
+
89
+ return { isSupported: isSupportedByController || isSupportedByPlatform };
90
+ }
91
+
92
+ private async handleGetEnvironment(): Promise<any> {
93
+ return this.environment;
94
+ }
95
+
96
+ private async handleGetBase(): Promise<any> {
97
+ return this.base;
98
+ }
99
+ }
@@ -0,0 +1,80 @@
1
+ import { IOConnectCore } from "@interopio/core";
2
+ import { generate } from "shortid";
3
+ import { Transaction } from "../common/types";
4
+ import logger from "../shared/logger";
5
+
6
+ /* eslint-disable @typescript-eslint/no-explicit-any */
7
+ export class TransactionsController {
8
+ private readonly transactionLocks: { [key in string]: Transaction<any> } = {};
9
+
10
+ private get logger(): IOConnectCore.Logger.API | undefined {
11
+ return logger.get("transactions.controller");
12
+ }
13
+
14
+ public completeTransaction(id: string, transactionData?: any): void {
15
+ if (typeof id !== "string") {
16
+ throw new Error(`Cannot complete the transaction, because the provided id is not a string: ${JSON.stringify(id)}`);
17
+ }
18
+
19
+ const foundTransaction = this.transactionLocks[id];
20
+
21
+ if (!foundTransaction) {
22
+ this.logger?.warn(`Cannot mark a transaction as complete, because there is not lock with id ${id}`);
23
+ return;
24
+ }
25
+
26
+ foundTransaction.lift(transactionData);
27
+ }
28
+
29
+ public failTransaction(id: string, reason: any): void {
30
+ const foundTransaction = this.transactionLocks[id];
31
+
32
+ if (!foundTransaction) {
33
+ this.logger?.warn(`Cannot mark a transaction as failed, because there is not lock with id ${id}`);
34
+ return;
35
+ }
36
+
37
+ foundTransaction.fail(reason);
38
+ }
39
+
40
+ public createTransaction<T>(operation: string, timeout: number): Transaction<T> {
41
+ const transaction: Transaction<T> = {} as Transaction<T>;
42
+
43
+ const transactionId = generate();
44
+
45
+ const transactionLock = new Promise<T>((resolve, reject) => {
46
+ let transactionLive = true;
47
+
48
+ transaction.lift = (args): void => {
49
+ transactionLive = false;
50
+ delete this.transactionLocks[transactionId];
51
+ resolve(args);
52
+ };
53
+
54
+ transaction.fail = (reason): void => {
55
+ transactionLive = false;
56
+ delete this.transactionLocks[transactionId];
57
+ reject(reason);
58
+ };
59
+
60
+ setTimeout(() => {
61
+ if (!transactionLive) {
62
+ return;
63
+ }
64
+
65
+ transactionLive = false;
66
+ this.logger?.warn(`Transaction for operation: ${operation} timed out.`);
67
+ delete this.transactionLocks[transactionId];
68
+ reject(`Transaction for operation: ${operation} timed out.`);
69
+ }, timeout);
70
+ });
71
+
72
+ transaction.lock = transactionLock;
73
+
74
+ transaction.id = transactionId;
75
+
76
+ this.transactionLocks[transactionId] = transaction;
77
+
78
+ return transaction;
79
+ }
80
+ }
package/src/factory.ts ADDED
@@ -0,0 +1,40 @@
1
+ import IOConnect, { IOConnectBrowser } from "@interopio/browser";
2
+ import { IOConnectBrowserPlatformFactoryFunction, IOConnectBrowserPlatform } from "../browser.platform";
3
+ import { Glue42API } from "./common/types";
4
+ import { checkIfPlacedInWorkspace, checkIsOpenerIOConnect } from "./fallbacks/browser";
5
+ import { fallbackToEnterprise } from "./fallbacks/dekstop";
6
+ import { IoC } from "./shared/ioc";
7
+
8
+ export const ioConnectBrowserPlatformFactory: IOConnectBrowserPlatformFactoryFunction = async (config: IOConnectBrowserPlatform.Config): Promise<{ io: IOConnectBrowser.API | Glue42API; platform?: IOConnectBrowserPlatform.API }> => {
9
+
10
+ // when running the package in Enterprise, we do not initialize anything from the platform
11
+ // because we cannot provide runtime environment configuration to Enterprise
12
+ // the same is valid when the platform is instructed to start as a client only
13
+ const desktopGlobal = (window as any).glue42gd || (window as any).iodesktop;
14
+
15
+ if (desktopGlobal) {
16
+ return fallbackToEnterprise(config);
17
+ }
18
+
19
+ // check if in Core and started by another platform and add the flag to the if
20
+ const isOpenerGlue = await checkIsOpenerIOConnect();
21
+
22
+ // if the platform is a window inside a workspace frame, it should also fallback to being a simple client
23
+ const isPlacedInWorkspace = checkIfPlacedInWorkspace();
24
+
25
+ if (config?.clientOnly || isOpenerGlue || isPlacedInWorkspace) {
26
+ const glue = config?.browserFactory ?
27
+ await config?.browserFactory(config?.browser) :
28
+ await IOConnect(config?.browser);
29
+
30
+ return { io: glue };
31
+ }
32
+
33
+ const ioc = new IoC(config);
34
+
35
+ await ioc.platform.ready();
36
+
37
+ const glue = ioc.platform.getClientGlue();
38
+
39
+ return { io: glue, platform: ioc?.platform.getPlatformApi() };
40
+ };
@@ -0,0 +1,47 @@
1
+ import { Glue42CoreMessageTypes } from "../common/constants";
2
+ import { defaultOpenerTimeoutMs } from "../common/defaultConfig";
3
+
4
+ export const checkIsOpenerIOConnect = (): Promise<boolean> => {
5
+
6
+ if (!window.opener) {
7
+ return Promise.resolve(false);
8
+ }
9
+
10
+ if (window.name.includes("g42-")) {
11
+ return Promise.resolve(true);
12
+ }
13
+
14
+ return new Promise<boolean>((resolve) => {
15
+
16
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
+ const pingListener = (event: MessageEvent<any>): void => {
18
+ const data = event.data?.glue42core;
19
+
20
+ if (!data || data.type !== Glue42CoreMessageTypes.platformReady.name) {
21
+ return;
22
+ }
23
+
24
+ window.removeEventListener("message", pingListener);
25
+
26
+ resolve(true);
27
+ };
28
+
29
+ window.addEventListener("message", pingListener);
30
+
31
+ const message = {
32
+ glue42core: {
33
+ type: Glue42CoreMessageTypes.platformPing.name
34
+ }
35
+ };
36
+
37
+ (window.opener as Window).postMessage(message, "*");
38
+
39
+ setTimeout(() => resolve(false), defaultOpenerTimeoutMs);
40
+ });
41
+ };
42
+
43
+ export const checkIfPlacedInWorkspace = (): boolean => {
44
+ const hasWspSuffix = window.name.indexOf("#wsp") !== -1;
45
+
46
+ return hasWspSuffix;
47
+ };
@@ -0,0 +1,21 @@
1
+ import { Glue42 } from "@glue42/desktop";
2
+ import IOConnect, { IOConnectBrowser } from "@interopio/browser";
3
+ import { IOConnectBrowserPlatform, IOConnectBrowserPlatformFactoryFunction } from "../../browser.platform";
4
+ import { Glue42API } from "../common/types";
5
+
6
+ export const fallbackToEnterprise: IOConnectBrowserPlatformFactoryFunction = async (config?: IOConnectBrowserPlatform.Config): Promise<{ io: IOConnectBrowser.API | Glue42API; platform?: IOConnectBrowserPlatform.API }> => {
7
+ const glue = config?.browserFactory ?
8
+ await config?.browserFactory(config?.browser) as unknown as Glue42.Glue :
9
+ await IOConnect(config?.browser) as Glue42.Glue;
10
+
11
+ if (config?.applications?.local?.length) {
12
+ // if fdc3 definition -> convert to gd definition and import
13
+ await glue.appManager.inMemory.import((config.applications.local as Glue42.AppManager.Definition[]), "merge");
14
+ }
15
+
16
+ if (config?.layouts?.local?.length) {
17
+ await glue.layouts.import(config.layouts.local as Glue42.Layouts.Layout[], "merge");
18
+ }
19
+
20
+ return { io: glue };
21
+ };
package/src/index.ts ADDED
@@ -0,0 +1,18 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { ioConnectBrowserPlatformFactory } from "./factory";
3
+
4
+ if (typeof window !== "undefined") {
5
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
6
+ (window as any).IOBrowserPlatform = ioConnectBrowserPlatformFactory;
7
+ }
8
+
9
+ const legacyGlobal = (window as any).glue42gd || (window as any).glue42core;
10
+ const ioGlobal = (window as any).iodesktop || (window as any).iobrowser;
11
+
12
+ if (!legacyGlobal && !ioGlobal) {
13
+
14
+ (window as any).iobrowser = { webStarted: false };
15
+
16
+ }
17
+
18
+ export default ioConnectBrowserPlatformFactory;
@@ -0,0 +1,235 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { IOConnectCore } from "@interopio/core";
3
+ import { IOConnectBrowser } from "@interopio/browser";
4
+ import { IOConnectBrowserPlatform } from "../../../../browser.platform";
5
+ import { objEqualFast } from "../../../shared/utils";
6
+ import { AppDirSetup, AppDirProcessingConfig, BaseApplicationData, ApplicationsMergeResult, AppDirectoryStateChange } from "../types";
7
+ import logger from "../../../shared/logger";
8
+ import { SessionStorageController } from "../../../storage/session";
9
+ import { RemoteWatcher } from "./remoteWatcher";
10
+ import { AsyncSequelizer } from "../../../shared/sequelizer";
11
+
12
+ export class AppDirectory {
13
+ private maxAllowedApplicationsInStore = 10000;
14
+ private readonly baseEventFlushDurationMs = 10;
15
+ private appsStateChange!: (state: AppDirectoryStateChange) => void;
16
+ private sequelizer!: AsyncSequelizer;
17
+
18
+ constructor(
19
+ private readonly sessionStorage: SessionStorageController,
20
+ private readonly remoteWatcher: RemoteWatcher
21
+ ) { }
22
+
23
+ public stop(): void {
24
+ this.remoteWatcher.stop();
25
+ }
26
+
27
+ public async start(setup: AppDirSetup): Promise<void> {
28
+ this.logger?.trace("Starting the application directory");
29
+ this.appsStateChange = setup.appsStateChange;
30
+ this.sequelizer = setup.sequelizer;
31
+
32
+ if (setup.config.local && setup.config.local.length) {
33
+ this.logger?.trace("Detected local applications, parsing...");
34
+
35
+ await this.processAppDefinitions(setup.config.local, { type: "inmemory", mode: "merge" });
36
+ }
37
+
38
+ if (setup.config.remote) {
39
+ this.logger?.trace("Detected remote app store configuration, starting the watcher...");
40
+ this.remoteWatcher.start(setup.config.remote, (apps) => this.processAppDefinitions(apps, { type: "remote", mode: "replace" }));
41
+ }
42
+ }
43
+
44
+ public processAppDefinitions(definitions: Array<IOConnectBrowser.AppManager.Definition | IOConnectBrowserPlatform.Applications.FDC3Definition>, config: AppDirProcessingConfig): Promise<void> {
45
+ return this.sequelizer.enqueue<void>(async () => {
46
+ const parsedDefinitions: BaseApplicationData[] = definitions.map((def) => this.parseDefinition(def));
47
+
48
+ const currentApps: BaseApplicationData[] = this.sessionStorage.getAllApps(config.type);
49
+
50
+ const mergeResult = this[config.mode](currentApps, parsedDefinitions);
51
+
52
+ if (mergeResult.readyApps.length > this.maxAllowedApplicationsInStore) {
53
+ throw new Error("Cannot save the app definitions, because the total number exceeds 10000, which is the limit.");
54
+ }
55
+
56
+ this.sessionStorage.overwriteApps(mergeResult.readyApps, config.type);
57
+
58
+ await this.announceApps(mergeResult);
59
+
60
+ });
61
+ }
62
+
63
+ public getAll(): Promise<BaseApplicationData[]> {
64
+ return this.sequelizer.enqueue<BaseApplicationData[]>(async () => {
65
+ const inMemory = this.sessionStorage.getAllApps("inmemory");
66
+ const remote = this.sessionStorage.getAllApps("remote");
67
+
68
+ return inMemory.concat(remote);
69
+ });
70
+ }
71
+
72
+ public exportInMemory(): Promise<IOConnectBrowser.AppManager.Definition[]> {
73
+ return this.sequelizer.enqueue<IOConnectBrowser.AppManager.Definition[]>(async () => {
74
+ const allBaseApps = this.sessionStorage.getAllApps("inmemory");
75
+
76
+ return allBaseApps.map(this.reverseParseDefinition);
77
+ });
78
+ }
79
+
80
+ public removeInMemory(name: string): Promise<BaseApplicationData | undefined> {
81
+ return this.sequelizer.enqueue<BaseApplicationData | undefined>(async () => {
82
+ return this.sessionStorage.removeApp(name, "inmemory");
83
+ });
84
+ }
85
+
86
+ private merge(currentApps: BaseApplicationData[], parsedDefinitions: BaseApplicationData[]): ApplicationsMergeResult {
87
+ const result: ApplicationsMergeResult = { readyApps: [], addedApps: [], changedApps: [], removedApps: [] };
88
+
89
+ const currentAppsTable = currentApps.reduce<{ [key in string]: BaseApplicationData }>((soFar, definition) => {
90
+ soFar[definition.name] = definition;
91
+ return soFar;
92
+ }, {});
93
+
94
+ parsedDefinitions.forEach((definition) => {
95
+ if (currentAppsTable[definition.name] && !objEqualFast(definition, currentAppsTable[definition.name])) {
96
+
97
+ currentAppsTable[definition.name] = definition;
98
+ result.changedApps.push(definition);
99
+ return;
100
+ }
101
+
102
+ if (!currentAppsTable[definition.name]) {
103
+ currentAppsTable[definition.name] = definition;
104
+ result.addedApps.push(definition);
105
+
106
+ return;
107
+ }
108
+
109
+ });
110
+
111
+ result.readyApps = Object.values(currentAppsTable);
112
+
113
+ return result;
114
+ }
115
+
116
+ private replace(currentApps: BaseApplicationData[], parsedDefinitions: BaseApplicationData[]): ApplicationsMergeResult {
117
+ const result: ApplicationsMergeResult = { readyApps: [], addedApps: [], changedApps: [], removedApps: [] };
118
+
119
+ const currentAppsTable = currentApps.reduce<{ [key in string]: BaseApplicationData }>((soFar, definition) => {
120
+ soFar[definition.name] = definition;
121
+ return soFar;
122
+ }, {});
123
+
124
+ parsedDefinitions.forEach((definition) => {
125
+
126
+ if (!currentAppsTable[definition.name]) {
127
+ result.addedApps.push(definition);
128
+ }
129
+
130
+ if (currentAppsTable[definition.name] && !objEqualFast(definition, currentAppsTable[definition.name])) {
131
+ result.changedApps.push(definition);
132
+ }
133
+
134
+ if (currentAppsTable[definition.name]) {
135
+ (currentAppsTable[definition.name] as any).isChecked = true;
136
+ }
137
+ });
138
+
139
+ result.removedApps = currentApps.filter((app) => !(app as any).isChecked);
140
+ result.readyApps = parsedDefinitions;
141
+
142
+ return result;
143
+ }
144
+
145
+ private reverseParseDefinition(definition: BaseApplicationData): IOConnectBrowser.AppManager.Definition {
146
+
147
+ const definitionDetails = definition.userProperties.details;
148
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
149
+ const { details, ...removedDetails } = definition.userProperties;
150
+
151
+ return {
152
+ name: definition.name,
153
+ type: (definition as any).type || "window",
154
+ title: definition.title,
155
+ version: definition.version,
156
+ icon: (definition as any).icon,
157
+ caption: (definition as any).caption,
158
+ details: definitionDetails,
159
+ customProperties: removedDetails
160
+ };
161
+ }
162
+
163
+ private parseDefinition(definition: IOConnectBrowser.AppManager.Definition | IOConnectBrowserPlatform.Applications.FDC3Definition): BaseApplicationData {
164
+
165
+ const glue42CoreAppProps = ["name", "title", "version", "customProperties", "icon", "caption", "type"];
166
+
167
+ const userProperties = Object.fromEntries(Object.entries(definition).filter(([key]) => !glue42CoreAppProps.includes(key)));
168
+
169
+ let createOptions: IOConnectBrowser.AppManager.DefinitionDetails = { url: "" };
170
+
171
+ if ((definition as any).manifest) {
172
+ // this is fdc3
173
+ const parsedManifest = JSON.parse((definition as IOConnectBrowserPlatform.Applications.FDC3Definition).manifest);
174
+
175
+ const url = parsedManifest.details?.url || parsedManifest.url;
176
+
177
+ if (!url || typeof url !== "string") {
178
+ throw new Error(`The FDC3 definition: ${definition.name} is not valid, because there is not url defined in the manifest`);
179
+ }
180
+
181
+ createOptions.url = url;
182
+ } else {
183
+ // this is GD
184
+ createOptions = (definition as IOConnectBrowser.AppManager.Definition).details;
185
+ }
186
+
187
+ const baseDefinition: BaseApplicationData = {
188
+ createOptions,
189
+ type: (definition as any).type || "window",
190
+ name: definition.name,
191
+ title: definition.title,
192
+ version: definition.version,
193
+ icon: (definition as any).icon,
194
+ caption: (definition as any).caption,
195
+ userProperties: {
196
+ ...userProperties,
197
+ ...(definition as any).customProperties
198
+ }
199
+ };
200
+
201
+ if (!baseDefinition.userProperties.details) {
202
+ baseDefinition.userProperties.details = createOptions;
203
+ }
204
+
205
+ // clears the undefined fields created by the assignment, which causes the same app import to trigger appChanged
206
+ Object
207
+ .keys(baseDefinition)
208
+ .forEach((key: string) => (baseDefinition as { [key in string]: any })[key] === undefined && delete (baseDefinition as { [key in string]: any })[key]);
209
+
210
+ return baseDefinition;
211
+ }
212
+
213
+ private get logger(): IOConnectCore.Logger.API | undefined {
214
+ return logger.get("applications.remote.directory");
215
+ }
216
+
217
+ private async announceApps(mergeResult: ApplicationsMergeResult): Promise<void> {
218
+
219
+ const appsStateChange: AppDirectoryStateChange = {
220
+ appsAdded: mergeResult.addedApps,
221
+ appsChanged: mergeResult.changedApps,
222
+ appsRemoved: mergeResult.removedApps
223
+ };
224
+
225
+ this.logger?.trace(`announcing a change in the app directory state: ${JSON.stringify(appsStateChange)}`);
226
+
227
+ this.appsStateChange(appsStateChange);
228
+
229
+ await this.waitEventFlush();
230
+ }
231
+
232
+ private waitEventFlush(): Promise<void> {
233
+ return new Promise((resolve) => setTimeout(resolve, this.baseEventFlushDurationMs));
234
+ }
235
+ }