@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,476 @@
1
+ /* eslint-disable indent */
2
+ /* eslint-disable @typescript-eslint/no-empty-function */
3
+ /* eslint-disable @typescript-eslint/no-explicit-any */
4
+ /* eslint-disable @typescript-eslint/no-unused-vars */
5
+ import { IOConnectCore } from "@interopio/core";
6
+ import { IOConnectBrowser } from "@interopio/browser";
7
+ import { BridgeOperation, InternalLayoutsConfig, InternalPlatformConfig, LibController, OperationCheckConfig, OperationCheckResult } from "../../common/types";
8
+ import { GlueController } from "../../controllers/glue";
9
+ import { SessionStorageController } from "../../storage/session";
10
+ import { LocalStoreController } from "../../storage/local";
11
+ import { operationCheckConfigDecoder, operationCheckResultDecoder } from "../../shared/decoders";
12
+ import logger from "../../shared/logger";
13
+ import { PromiseWrap } from "../../shared/promisePlus";
14
+ import { extractErrorMsg, objEqual } from "../../shared/utils";
15
+ import { allLayoutsFullConfigDecoder, allLayoutsSummariesResultDecoder, getAllLayoutsConfigDecoder, layoutsImportConfigDecoder, layoutsOperationTypesDecoder, optionalSimpleLayoutResult, permissionStateResultDecoder, restoreLayoutConfigDecoder, saveLayoutConfigDecoder, setDefaultGlobalConfigDecoder, simpleAvailabilityResultDecoder, simpleLayoutConfigDecoder } from "./decoders";
16
+ import { IdbLayoutsStore } from "./idbStore";
17
+ import { AllLayoutsFullConfig, AllLayoutsSummariesResult, GetAllLayoutsConfig, LayoutsImportConfig, LayoutsOperationTypes, OptionalSimpleLayoutResult, RestoreLayoutConfig, SaveLayoutConfig, SimpleLayoutConfig, SimpleLayoutResult, PermissionStateResult, SimpleAvailabilityResult, LayoutEvent, DefaultGlobalLayoutData } from "./types";
18
+ import { Builder } from "./global/builder";
19
+ import { Restorer } from "./global/restorer";
20
+ import { defaultPermissionTimeoutMS } from "./constants";
21
+ import { IOConnectBrowserPlatform } from "../../../browser.platform";
22
+ import {
23
+ CallbackRegistry,
24
+ UnsubscribeFunction,
25
+ } from "callback-registry";
26
+
27
+ export class LayoutsController implements LibController {
28
+
29
+ private started = false;
30
+ private config!: InternalLayoutsConfig;
31
+
32
+ public operations: { [key in LayoutsOperationTypes]: BridgeOperation } = {
33
+ get: { name: "get", dataDecoder: simpleLayoutConfigDecoder, resultDecoder: optionalSimpleLayoutResult, execute: this.handleGetLayout.bind(this) },
34
+ getAll: { name: "getAll", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsSummariesResultDecoder, execute: this.handleGetAll.bind(this) },
35
+ export: { name: "export", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsFullConfigDecoder, execute: this.handleExport.bind(this) },
36
+ import: { name: "import", dataDecoder: layoutsImportConfigDecoder, execute: this.handleImport.bind(this) },
37
+ remove: { name: "remove", dataDecoder: simpleLayoutConfigDecoder, execute: this.handleRemove.bind(this) },
38
+ save: { name: "save", dataDecoder: saveLayoutConfigDecoder, execute: this.handleSave.bind(this) },
39
+ restore: { name: "restore", dataDecoder: restoreLayoutConfigDecoder, execute: this.handleRestore.bind(this) },
40
+ getGlobalPermissionState: { name: "getGlobalPermissionState", resultDecoder: permissionStateResultDecoder, execute: this.handleGetGlobalPermissionState.bind(this) },
41
+ requestGlobalPermission: { name: "requestGlobalPermission", resultDecoder: simpleAvailabilityResultDecoder, execute: this.handleRequestGlobalPermission.bind(this) },
42
+ checkGlobalActivated: { name: "checkGlobalActivated", resultDecoder: simpleAvailabilityResultDecoder, execute: this.handleCheckGlobalActivated.bind(this) },
43
+ operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder, execute: this.handleOperationCheck.bind(this) },
44
+ getDefaultGlobal: { name: "getDefaultGlobal", resultDecoder: optionalSimpleLayoutResult, execute: this.handleGetDefaultGlobal.bind(this) },
45
+ setDefaultGlobal: { name: "setDefaultGlobal", dataDecoder: setDefaultGlobalConfigDecoder, execute: this.handleSetDefaultGlobal.bind(this) },
46
+ clearDefaultGlobal: { name: "clearDefaultGlobal", execute: this.handleClearDefaultGlobal.bind(this) }
47
+ };
48
+
49
+ constructor(
50
+ private readonly glueController: GlueController,
51
+ private readonly idbStore: IdbLayoutsStore,
52
+ private readonly sessionStore: SessionStorageController,
53
+ private readonly localStore: LocalStoreController,
54
+ private readonly globalBuilder: Builder,
55
+ private readonly globalRestorer: Restorer,
56
+ private readonly registry: CallbackRegistry
57
+ ) {}
58
+
59
+ private get logger(): IOConnectCore.Logger.API | undefined {
60
+ return logger.get("layouts.controller");
61
+ }
62
+
63
+ public handlePlatformShutdown(): void {
64
+ this.started = false;
65
+
66
+ this.registry.clear();
67
+
68
+ if (this.config.mode === "idb") {
69
+ this.idbStore.clear("Global").catch((error) => this.logger?.warn(extractErrorMsg(error)));
70
+ this.idbStore.clear("Workspace").catch((error) => this.logger?.warn(extractErrorMsg(error)));
71
+ }
72
+ }
73
+
74
+ public async start(config: InternalPlatformConfig): Promise<void> {
75
+ this.config = config.layouts;
76
+
77
+ this.logger?.trace(`initializing with mode: ${this.config.mode}`);
78
+
79
+ if (this.config.local && this.config.local.length) {
80
+
81
+ const localGlobalLayouts = this.config.local.filter((layout) => layout.type === "Global");
82
+ const localWorkspaceLayouts = this.config.local.filter((layout) => layout.type === "Workspace");
83
+
84
+ await Promise.all([
85
+ this.mergeImport(localGlobalLayouts, "Global"),
86
+ this.mergeImport(localWorkspaceLayouts, "Workspace")
87
+ ]);
88
+ }
89
+
90
+ this.started = true;
91
+
92
+ this.logger?.trace("initialization is completed");
93
+ }
94
+
95
+ public async handleControl(controlMessage: IOConnectBrowserPlatform.ControlMessage): Promise<any> {
96
+ if (!this.started) {
97
+ new Error("Cannot handle this windows control message, because the controller has not been started");
98
+ }
99
+
100
+ const layoutsData = controlMessage.data;
101
+
102
+ const commandId = controlMessage.commandId;
103
+
104
+ const operationValidation = layoutsOperationTypesDecoder.run(controlMessage.operation);
105
+
106
+ if (!operationValidation.ok) {
107
+ throw new Error(`This layouts request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(operationValidation.error)}`);
108
+ }
109
+
110
+ const operationName: LayoutsOperationTypes = operationValidation.result;
111
+
112
+ const incomingValidation = this.operations[operationName].dataDecoder?.run(layoutsData);
113
+
114
+ if (incomingValidation && !incomingValidation.ok) {
115
+ throw new Error(`Layouts request for ${operationName} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(incomingValidation.error)}`);
116
+ }
117
+
118
+ this.logger?.debug(`[${commandId}] ${operationName} command is valid with data: ${JSON.stringify(layoutsData)}`);
119
+
120
+ const result = await this.operations[operationName].execute(layoutsData, commandId, controlMessage.callerId, controlMessage.callerType);
121
+
122
+ const resultValidation = this.operations[operationName].resultDecoder?.run(result);
123
+
124
+ if (resultValidation && !resultValidation.ok) {
125
+ throw new Error(`Layouts request for ${operationName} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(resultValidation.error)}`);
126
+ }
127
+
128
+ this.logger?.trace(`[${commandId}] ${operationName} command was executed successfully`);
129
+
130
+ return result;
131
+ }
132
+
133
+ public async handleSave(config: SaveLayoutConfig, commandId: string): Promise<SimpleLayoutResult> {
134
+ this.logger?.trace(`[${commandId}] handling save layout with config: ${JSON.stringify(config)}`);
135
+
136
+ await this.checkRequestPermission("save");
137
+
138
+ this.logger?.trace(`[${commandId}] the required permissions are granted, proceeding.`);
139
+
140
+ const layout = await this.globalBuilder.saveGlobalLayout(config, commandId);
141
+
142
+ this.logger?.trace(`[${commandId}] layout ${config.layout.name} was saved successfully`);
143
+
144
+ return { layout };
145
+ }
146
+
147
+ public async handleRestore(config: RestoreLayoutConfig, commandId: string, callerId?: string, callerType?: "plugin" | "client"): Promise<void> {
148
+ this.logger?.trace(`[${commandId}] handling restore layout with config: ${JSON.stringify(config)}`);
149
+
150
+ await this.checkRequestPermission("restore", config.layout.timeout);
151
+
152
+ await this.globalRestorer.restoreGlobalLayout(config, commandId, callerId, callerType);
153
+
154
+ this.logger?.trace(`[${commandId}] layout ${config.layout.name} was restored successfully`);
155
+ }
156
+
157
+ public async handleGetAll(config: GetAllLayoutsConfig, commandId: string): Promise<AllLayoutsSummariesResult> {
158
+ this.logger?.trace(`[${commandId}] handling get all layout summaries request for type: ${config.type}`);
159
+
160
+ const allLayouts = await this.getAll(config.type);
161
+
162
+ const summaries = allLayouts.map<IOConnectBrowser.Layouts.LayoutSummary>((layout) => {
163
+ return {
164
+ name: layout.name,
165
+ type: layout.type,
166
+ context: layout.context,
167
+ metadata: layout.metadata
168
+ };
169
+ });
170
+
171
+ this.logger?.trace(`[${commandId}] all summaries have been compiled, responding to caller`);
172
+
173
+ return { summaries };
174
+ }
175
+
176
+ public async handleExport(config: GetAllLayoutsConfig, commandId: string): Promise<AllLayoutsFullConfig> {
177
+ this.logger?.trace(`[${commandId}] handling get all layout full request for type: ${config.type}`);
178
+
179
+ const layouts = await this.getAll(config.type);
180
+
181
+ this.logger?.trace(`[${commandId}] full layouts collection have been compiled, responding to caller`);
182
+
183
+ return { layouts };
184
+ }
185
+
186
+ public async handleImport(config: LayoutsImportConfig, commandId: string): Promise<void> {
187
+ this.logger?.trace(`[${commandId}] handling mass import request for layout names: ${config.layouts.map((l) => l.name).join(", ")}`);
188
+
189
+ const importExecution = config.mode === "merge" ? this.mergeImport.bind(this) : this.replaceImport.bind(this);
190
+
191
+ this.logger?.trace(`[${commandId}] importing the layouts in ${config.mode} mode`);
192
+
193
+ const workspaceLayouts = config.layouts.filter((layout) => layout.type === "Workspace");
194
+ const globalLayouts = config.layouts.filter((layout) => layout.type === "Global");
195
+
196
+ await Promise.all([
197
+ importExecution(globalLayouts, "Global", config.isManagerOperation),
198
+ importExecution(workspaceLayouts, "Workspace", config.isManagerOperation)
199
+ ]);
200
+
201
+ this.logger?.trace(`[${commandId}] mass import completed, responding to caller`);
202
+ }
203
+
204
+ public async handleRemove(config: SimpleLayoutConfig, commandId: string): Promise<void> {
205
+ this.logger?.trace(`[${commandId}] handling remove request for ${JSON.stringify(config)}`);
206
+
207
+ const layout = (await this.getAll(config.type)).find((l) => l.name === config.name && l.type === config.type);
208
+
209
+ if (layout) {
210
+ await this.delete(config.name, config.type);
211
+ this.emitStreamData("layoutRemoved", layout);
212
+ }
213
+
214
+ const operationMessage = layout ? "has been removed" : "has not been removed, because it does not exist";
215
+
216
+ this.logger?.trace(`[${commandId}] ${config.name} of type ${config.type} ${operationMessage}`);
217
+ }
218
+
219
+ public async handleGetLayout(config: SimpleLayoutConfig, commandId: string): Promise<OptionalSimpleLayoutResult> {
220
+ this.logger?.trace(`[${commandId}] handling get layout request for name: ${config.name} and type: ${config.type}`);
221
+
222
+ const allLayouts = await this.getAll(config.type);
223
+
224
+ const layout = allLayouts.find((l) => l.name === config.name);
225
+
226
+ this.logger?.trace(`[${commandId}] request completed, responding to the caller`);
227
+
228
+ return { layout };
229
+ }
230
+
231
+ public onUserLayoutEvent(callback: (data: { operation: LayoutEvent, layout: IOConnectBrowser.Layouts.Layout }) => void): UnsubscribeFunction {
232
+ return this.registry.add("layoutEvent", callback);
233
+ }
234
+
235
+ private async handleOperationCheck(config: OperationCheckConfig): Promise<OperationCheckResult> {
236
+ const operations = Object.keys(this.operations);
237
+
238
+ const isSupported = operations.some((operation) => operation.toLowerCase() === config.operation.toLowerCase());
239
+
240
+ return { isSupported };
241
+ }
242
+
243
+ public async handleGetGlobalPermissionState(args: unknown, commandId: string): Promise<PermissionStateResult> {
244
+ this.logger?.trace(`[${commandId}] handling Get Global Permission State request`);
245
+
246
+ const { state }: { state: "granted" | "prompt" | "denied" } = await (navigator as any).permissions.query({ name: "window-placement" });
247
+
248
+ this.logger?.trace(`[${commandId}] request completed with state: ${state}, responding to the caller`);
249
+
250
+ return { state };
251
+ }
252
+
253
+ public async handleRequestGlobalPermission(args: unknown, commandId: string): Promise<SimpleAvailabilityResult> {
254
+ this.logger?.trace(`[${commandId}] handling Request Global Permission command`);
255
+
256
+ const { state }: { state: "granted" | "prompt" | "denied" } = await (navigator as any).permissions.query({ name: "window-placement" });
257
+
258
+ if (state === "granted") {
259
+ return { isAvailable: true };
260
+ }
261
+
262
+ if (state === "denied") {
263
+ return { isAvailable: false };
264
+ }
265
+
266
+ try {
267
+ await (window as any).getScreenDetails();
268
+
269
+ this.logger?.trace(`[${commandId}] request completed, responding to the caller`);
270
+
271
+ return { isAvailable: true };
272
+ } catch (error) {
273
+ this.logger?.trace(`[${commandId}] request completed, responding to the caller`);
274
+
275
+ return { isAvailable: false };
276
+ }
277
+ }
278
+
279
+ public async handleCheckGlobalActivated(args: unknown, commandId: string): Promise<SimpleAvailabilityResult> {
280
+ this.logger?.trace(`[${commandId}] handling Check Global Activated request`);
281
+
282
+ this.logger?.trace(`[${commandId}] request completed, responding to the caller`);
283
+
284
+ return { isAvailable: true };
285
+ }
286
+
287
+ private async handleGetDefaultGlobal(commandId: string): Promise<OptionalSimpleLayoutResult> {
288
+ this.logger?.trace(`[${commandId}] handling Get Default Global request`);
289
+
290
+ const defaultGlobalLayoutName = this.localStore.getDefaultGlobalLayoutName();
291
+ const allGlobalLayouts = await this.getAll("Global");
292
+ const defaultGlobalLayout = allGlobalLayouts.find((layout) => layout.name === defaultGlobalLayoutName);
293
+
294
+ this.logger?.trace(`[${commandId}] request completed, responding to the caller`);
295
+
296
+ return { layout: defaultGlobalLayout };
297
+ }
298
+
299
+ private async handleSetDefaultGlobal(config: DefaultGlobalLayoutData, commandId: string): Promise<void> {
300
+ this.logger?.trace(`[${commandId}] handling Set Default Global request for name: ${config.name}`);
301
+
302
+ const allGlobalLayouts = await this.getAll("Global");
303
+ const layout = allGlobalLayouts.find((layout) => layout.name === config.name);
304
+
305
+ if(!layout) {
306
+ throw new Error(`Layout "${config.name}" doesn't exist`);
307
+ }
308
+
309
+ this.localStore.saveDefaultGlobalLayout(config.name);
310
+
311
+ this.logger?.trace(`[${commandId}] request completed, responding to the caller`);
312
+ }
313
+
314
+ private async handleClearDefaultGlobal(commandId: string): Promise<void> {
315
+ this.logger?.trace(`[${commandId}] handling Clear Default Global request`);
316
+
317
+ this.localStore.clearDefaultGlobalLayout();
318
+
319
+ this.logger?.trace(`[${commandId}] request completed, responding to the caller`);
320
+ }
321
+
322
+ private emitStreamData(operation: "layoutChanged" | "layoutAdded" | "layoutRemoved", data: IOConnectBrowser.Layouts.Layout, isManagerOperation?: boolean): void {
323
+ this.logger?.trace(`sending notification of event: ${operation} with data: ${JSON.stringify(data)}`);
324
+
325
+ this.glueController.pushSystemMessage("layouts", operation, data);
326
+
327
+ if (isManagerOperation) {
328
+ return;
329
+ }
330
+
331
+ this.registry.execute("layoutEvent", { operation, layout: data });
332
+ }
333
+
334
+ private async mergeImport(layouts: IOConnectBrowser.Layouts.Layout[], type: IOConnectBrowser.Layouts.LayoutType, isManagerOperation?: boolean): Promise<void> {
335
+ const currentLayouts = await this.getAll(type);
336
+ const pendingEvents: Array<{ operation: "layoutChanged" | "layoutAdded" | "layoutRemoved"; layout: IOConnectBrowser.Layouts.Layout }> = [];
337
+
338
+ for (const layout of layouts) {
339
+ const defCurrentIdx = currentLayouts.findIndex((app) => app.name === layout.name);
340
+
341
+ if (defCurrentIdx > -1 && !objEqual(layout, currentLayouts[defCurrentIdx])) {
342
+ this.logger?.trace(`change detected at layout ${layout.name}`);
343
+ pendingEvents.push({ operation: "layoutChanged", layout });
344
+
345
+ currentLayouts[defCurrentIdx] = layout;
346
+
347
+ continue;
348
+ }
349
+
350
+ if (defCurrentIdx < 0) {
351
+ this.logger?.trace(`new layout: ${layout.name} detected, adding and announcing`);
352
+ pendingEvents.push({ operation: "layoutAdded", layout });
353
+ currentLayouts.push(layout);
354
+ }
355
+ }
356
+
357
+ await this.cleanSave(currentLayouts, type);
358
+ await this.announceEvents(pendingEvents, isManagerOperation);
359
+ }
360
+
361
+ private async replaceImport(layouts: IOConnectBrowser.Layouts.Layout[], type: IOConnectBrowser.Layouts.LayoutType, isManagerOperation?: boolean): Promise<void> {
362
+ const currentLayouts = await this.getAll(type);
363
+ const pendingEvents: Array<{ operation: "layoutChanged" | "layoutAdded" | "layoutRemoved"; layout: IOConnectBrowser.Layouts.Layout }> = [];
364
+
365
+ for (const layout of layouts) {
366
+ const defCurrentIdx = currentLayouts.findIndex((app) => app.name === layout.name);
367
+
368
+ if (defCurrentIdx < 0) {
369
+ this.logger?.trace(`new layout: ${layout.name} detected, adding and announcing`);
370
+ pendingEvents.push({ operation: "layoutAdded", layout });
371
+ continue;
372
+ }
373
+
374
+ if (!objEqual(layout, currentLayouts[defCurrentIdx])) {
375
+ this.logger?.trace(`change detected at layout ${layout.name}`);
376
+ pendingEvents.push({ operation: "layoutChanged", layout });
377
+ }
378
+
379
+ currentLayouts.splice(defCurrentIdx, 1);
380
+ }
381
+
382
+ // everything that is left in the old snap here, means it is removed in the latest one
383
+ currentLayouts.forEach((layout) => {
384
+ this.logger?.trace(`layout ${layout.name} missing, removing and announcing`);
385
+ pendingEvents.push({ operation: "layoutRemoved", layout });
386
+ });
387
+
388
+ await this.cleanSave(layouts, type);
389
+ await this.announceEvents(pendingEvents, isManagerOperation);
390
+ }
391
+
392
+ private async announceEvents(events: Array<{ operation: "layoutChanged" | "layoutAdded" | "layoutRemoved", layout: IOConnectBrowser.Layouts.Layout }>, isManagerOperation?: boolean): Promise<void> {
393
+
394
+ let batchCount = 0;
395
+
396
+ for (const event of events) {
397
+ ++batchCount;
398
+
399
+ if (batchCount % 10 === 0) {
400
+ await this.waitEventFlush();
401
+ }
402
+
403
+ this.emitStreamData(event.operation, event.layout, isManagerOperation);
404
+ }
405
+ }
406
+
407
+ private async getAll(type: IOConnectBrowser.Layouts.LayoutType): Promise<IOConnectBrowser.Layouts.Layout[]> {
408
+ let all: IOConnectBrowser.Layouts.Layout[];
409
+
410
+ if (this.config.mode === "idb") {
411
+ all = await this.idbStore.getAll(type);
412
+ } else {
413
+ all = this.sessionStore.getLayoutSnapshot(type).layouts;
414
+ }
415
+
416
+ return all;
417
+ }
418
+
419
+ private async cleanSave(layouts: IOConnectBrowser.Layouts.Layout[], type: IOConnectBrowser.Layouts.LayoutType): Promise<void> {
420
+ if (this.config.mode === "idb") {
421
+ await this.idbStore.clear(type);
422
+
423
+ for (const layout of layouts) {
424
+ await this.idbStore.store(layout, layout.type);
425
+ }
426
+ return;
427
+ }
428
+
429
+ this.sessionStore.saveLayoutSnapshot({ layouts }, type);
430
+ }
431
+
432
+ private async delete(name: string, type: IOConnectBrowser.Layouts.LayoutType): Promise<void> {
433
+ if (this.config.mode === "idb") {
434
+ await this.idbStore.delete(name, type);
435
+ return;
436
+ }
437
+
438
+ const all = this.sessionStore.getLayoutSnapshot(type).layouts;
439
+
440
+ const idxToRemove = all.findIndex((l) => l.name === name);
441
+
442
+ if (idxToRemove > -1) {
443
+ all.splice(idxToRemove, 1);
444
+ }
445
+
446
+ this.sessionStore.saveLayoutSnapshot({ layouts: all }, type);
447
+ }
448
+
449
+ private waitEventFlush(): Promise<void> {
450
+ return new Promise((resolve) => setTimeout(resolve, 10));
451
+ }
452
+
453
+ private async checkRequestPermission(operation: "save" | "restore", timeoutMS: number = defaultPermissionTimeoutMS): Promise<void> {
454
+ if ((window as any).gtf) {
455
+ return;
456
+ }
457
+
458
+ // disabling a few rules is necessary, because at this time the DOM typings where not updated with the latest window-placement permission
459
+ const { state } = await (navigator as any).permissions.query({ name: "window-placement" });
460
+
461
+ switch (state) {
462
+ case "granted":
463
+ return;
464
+ case "prompt":
465
+ try {
466
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
467
+ await PromiseWrap(() => (window as any).getScreenDetails() as Promise<any>, timeoutMS, "Timeout waiting for user permission for Multi-Screen Window Placement");
468
+ return;
469
+ } catch (error) {
470
+ throw new Error(`Cannot complete operation ${operation} for Global Layouts, because the user has not granted the Multi-Screen Window Placement permission`);
471
+ }
472
+ case "denied":
473
+ throw new Error(`Cannot complete operation ${operation} for Global Layouts, because the user has denied the Multi-Screen Window Placement permission`);
474
+ }
475
+ }
476
+ }
@@ -0,0 +1,132 @@
1
+ import { IOConnectBrowser } from "@interopio/browser";
2
+ import { Decoder, oneOf, constant, anyJson, array, object, optional, boolean } from "decoder-validate";
3
+ import { glueLayoutDecoder, layoutSummaryDecoder, nonEmptyStringDecoder, nonNegativeNumberDecoder, windowBoundsDecoder, layoutTypeDecoder } from "../../shared/decoders";
4
+ import { GetAllLayoutsConfig, AllLayoutsSummariesResult, AllLayoutsFullConfig, LayoutsOperationTypes, SimpleLayoutConfig, SimpleLayoutResult, OptionalSimpleLayoutResult, LayoutsImportConfig, SaveLayoutConfig, RestoreLayoutConfig, RawWindowsLayoutDataRequestConfig, SaveRequestClientResponse, WindowRawLayoutData, PermissionStateResult, SimpleAvailabilityResult, WindowsRawLayoutData, WorkspaceWindowRawLayoutData, DefaultGlobalLayoutData } from "./types";
5
+
6
+ export const layoutsOperationTypesDecoder: Decoder<LayoutsOperationTypes> = oneOf<"get" | "getAll" | "export" | "import" | "remove" | "save" | "restore" | "getGlobalPermissionState" | "requestGlobalPermission" | "checkGlobalActivated" | "operationCheck" | "getDefaultGlobal" | "setDefaultGlobal" | "clearDefaultGlobal" >(
7
+ constant("get"),
8
+ constant("getAll"),
9
+ constant("export"),
10
+ constant("import"),
11
+ constant("remove"),
12
+ constant("save"),
13
+ constant("restore"),
14
+ constant("getGlobalPermissionState"),
15
+ constant("checkGlobalActivated"),
16
+ constant("requestGlobalPermission"),
17
+ constant("operationCheck"),
18
+ constant("getDefaultGlobal"),
19
+ constant("setDefaultGlobal"),
20
+ constant("clearDefaultGlobal")
21
+ );
22
+
23
+ export const newLayoutOptionsDecoder: Decoder<IOConnectBrowser.Layouts.NewLayoutOptions> = object({
24
+ name: nonEmptyStringDecoder,
25
+ context: optional(anyJson()),
26
+ metadata: optional(anyJson()),
27
+ instances: optional(array(nonEmptyStringDecoder)),
28
+ ignoreInstances: optional(array(nonEmptyStringDecoder))
29
+ });
30
+
31
+ export const restoreOptionsDecoder: Decoder<IOConnectBrowser.Layouts.RestoreOptions> = object({
32
+ name: nonEmptyStringDecoder,
33
+ context: optional(anyJson()),
34
+ closeRunningInstance: optional(boolean()),
35
+ closeMe: optional(boolean()),
36
+ timeout: optional(nonNegativeNumberDecoder)
37
+ });
38
+
39
+ export const simpleLayoutConfigDecoder: Decoder<SimpleLayoutConfig> = object({
40
+ name: nonEmptyStringDecoder,
41
+ type: layoutTypeDecoder
42
+ });
43
+
44
+ export const getAllLayoutsConfigDecoder: Decoder<GetAllLayoutsConfig> = object({
45
+ type: layoutTypeDecoder
46
+ });
47
+
48
+ export const saveLayoutConfigDecoder: Decoder<SaveLayoutConfig> = object({
49
+ layout: newLayoutOptionsDecoder
50
+ });
51
+
52
+ export const restoreLayoutConfigDecoder: Decoder<RestoreLayoutConfig> = object({
53
+ layout: restoreOptionsDecoder
54
+ });
55
+
56
+ export const allLayoutsFullConfigDecoder: Decoder<AllLayoutsFullConfig> = object({
57
+ layouts: array(glueLayoutDecoder)
58
+ });
59
+
60
+ export const importModeDecoder: Decoder<"replace" | "merge"> = oneOf<"replace" | "merge">(
61
+ constant("replace"),
62
+ constant("merge")
63
+ );
64
+
65
+ export const layoutsImportConfigDecoder: Decoder<LayoutsImportConfig> = object({
66
+ layouts: array(glueLayoutDecoder),
67
+ mode: importModeDecoder,
68
+ isManagerOperation: optional(boolean())
69
+ });
70
+
71
+ export const allLayoutsSummariesResultDecoder: Decoder<AllLayoutsSummariesResult> = object({
72
+ summaries: array(layoutSummaryDecoder)
73
+ });
74
+
75
+ export const simpleLayoutResult: Decoder<SimpleLayoutResult> = object({
76
+ layout: glueLayoutDecoder
77
+ });
78
+
79
+ export const optionalSimpleLayoutResult: Decoder<OptionalSimpleLayoutResult> = object({
80
+ layout: optional(glueLayoutDecoder)
81
+ });
82
+
83
+ export const setDefaultGlobalConfigDecoder: Decoder<DefaultGlobalLayoutData> = object({
84
+ name: nonEmptyStringDecoder
85
+ });
86
+
87
+ export const rawWindowsLayoutDataRequestConfigDecoder: Decoder<RawWindowsLayoutDataRequestConfig> = object({
88
+ layoutType: oneOf<"Global" | "Workspace">(
89
+ constant("Global"),
90
+ constant("Workspace")
91
+ ),
92
+ layoutName: nonEmptyStringDecoder,
93
+ context: optional(anyJson()),
94
+ instances: optional(array(nonEmptyStringDecoder)),
95
+ ignoreInstances: optional(array(nonEmptyStringDecoder))
96
+ });
97
+
98
+ export const saveRequestClientResponseDecoder: Decoder<SaveRequestClientResponse> = object({
99
+ windowContext: optional(anyJson()),
100
+ });
101
+
102
+ export const fullSaveRequestResponseDecoder: Decoder<WindowRawLayoutData> = object({
103
+ bounds: windowBoundsDecoder,
104
+ windowContext: optional(anyJson()),
105
+ url: nonEmptyStringDecoder,
106
+ name: nonEmptyStringDecoder,
107
+ application: nonEmptyStringDecoder,
108
+ windowId: nonEmptyStringDecoder,
109
+ initialContext: optional(anyJson())
110
+ });
111
+
112
+ export const workspaceWindowRawLayoutDataDecoder: Decoder<WorkspaceWindowRawLayoutData> = object({
113
+ windowContext: optional(anyJson()),
114
+ windowId: nonEmptyStringDecoder,
115
+ frameId: nonEmptyStringDecoder
116
+ });
117
+
118
+ export const windowsRawLayoutDataDecoder: Decoder<WindowsRawLayoutData> = object({
119
+ windows: array(fullSaveRequestResponseDecoder)
120
+ });
121
+
122
+ export const permissionStateResultDecoder: Decoder<PermissionStateResult> = object({
123
+ state: oneOf<"prompt" | "granted" | "denied">(
124
+ constant("prompt"),
125
+ constant("denied"),
126
+ constant("granted")
127
+ )
128
+ });
129
+
130
+ export const simpleAvailabilityResultDecoder: Decoder<SimpleAvailabilityResult> = object({
131
+ isAvailable: boolean()
132
+ });