@interopio/fdc3 2.3.3 → 2.4.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/fdc3.es.js CHANGED
@@ -1228,88 +1228,11 @@ const defaultContextProps = ["type"];
1228
1228
  const defaultGlue42APIs = ["contexts", "channels", "interop", "intents", "appManager", "windows"];
1229
1229
  const glueChannelNamePrefix = "___channel___";
1230
1230
  const fdc3NothingContextType = "fdc3.nothing";
1231
- const Glue42EnterpriseNoAppWindow = "no-app-window";
1232
1231
  const RaiseTimeoutMs = 75 * 1000;
1233
1232
  const IntentsMethodPrefix = "Tick42.FDC3.Intents.";
1234
- const Fdc3SupportedIntentTypes = {
1235
- "CreateInteraction": [
1236
- "fdc3.contactList",
1237
- "fdc3.interaction"
1238
- ],
1239
- "StartCall": [
1240
- "fdc3.contact",
1241
- "fdc3.contactList"
1242
- ],
1243
- "StartChat": [
1244
- "fdc3.contact",
1245
- "fdc3.contactList",
1246
- "fdc3.chat.initSettings"
1247
- ],
1248
- "StartEmail": [
1249
- "fdc3.email"
1250
- ],
1251
- "SendChatMessage": [
1252
- "fdc3.chat.message"
1253
- ],
1254
- "ViewAnalysis": [
1255
- "fdc3.instrument",
1256
- "fdc3.organization",
1257
- "fdc3.portfolio"
1258
- ],
1259
- "ViewChat": [
1260
- "fdc3.chat.room",
1261
- "fdc3.contact",
1262
- "fdc3.contactList"
1263
- ],
1264
- "ViewChart": [
1265
- "fdc3.chart",
1266
- "fdc3.instrument",
1267
- "fdc3.instrumentList",
1268
- "fdc3.portfolio",
1269
- "fdc3.position"
1270
- ],
1271
- "ViewHoldings": [
1272
- "fdc3.instrument",
1273
- "fdc3.instrumentList",
1274
- "fdc3.organization"
1275
- ],
1276
- "ViewInstrument": [
1277
- "fdc3.instrument"
1278
- ],
1279
- "ViewInteractions": [
1280
- "fdc3.contact",
1281
- "fdc3.instrument",
1282
- "fdc3.organization"
1283
- ],
1284
- "ViewMessages": [
1285
- "fdc3.chat.searchCriteria"
1286
- ],
1287
- "ViewNews": [
1288
- "fdc3.country",
1289
- "fdc3.instrument",
1290
- "fdc3.instrumentList",
1291
- "fdc3.organization",
1292
- "fdc3.portfolio"
1293
- ],
1294
- "ViewOrders": [
1295
- "fdc3.contact",
1296
- "fdc3.instrument",
1297
- "fdc3.organization"
1298
- ],
1299
- "ViewProfile": [
1300
- "fdc3.contact",
1301
- "fdc3.organization"
1302
- ],
1303
- "ViewQuote": [
1304
- "fdc3.instrument"
1305
- ],
1306
- "ViewResearch": [
1307
- "fdc3.contact",
1308
- "fdc3.instrument",
1309
- "fdc3.organization"
1310
- ]
1311
- };
1312
1233
  const IO_ERRORS = errors.intents;
1234
+ const BrowserClientControlMethodName = "T42.Web.Client.Control";
1235
+ const DesktopClientControlMethodName = "T42.Channels.Command";
1313
1236
 
1314
1237
  const ioConnectFDC3SystemMethod = "FDC3.Collaborate";
1315
1238
  const PrivateChannelPrefix = "___privateFDC3Channel___";
@@ -2271,9 +2194,8 @@ class GlueController {
2271
2194
  const latestTypePathValue = { path: "latest_fdc3_type", value: this.channelsParser.mapFDC3TypeToChannelsDelimiter(context.type) };
2272
2195
  await this.contextsSetPaths(contextId, [{ path: `data.${path}`, value: value }, latestTypePathValue]);
2273
2196
  }
2274
- async channelsUpdate(channelId, context) {
2275
- const { path, value } = this.channelsParser.parseFDC3ContextToGlueContexts(context);
2276
- return this.glue.channels.publish({ [path]: value }, channelId);
2197
+ async channelsUpdate(data, options) {
2198
+ return this.glue.channels.publish(data, options);
2277
2199
  }
2278
2200
  async joinChannel(channelId) {
2279
2201
  return this.glue.channels.join(channelId);
@@ -2322,9 +2244,9 @@ class GlueController {
2322
2244
  getInteropMethods(filter) {
2323
2245
  return this.glue.interop.methods(filter);
2324
2246
  }
2325
- channelsSubscribe(callback, contextType) {
2247
+ legacyChannelsSubscribe(callback, contextType) {
2326
2248
  const didReplay = { replayed: false };
2327
- return this.glue.channels.subscribe((_, contextData, updaterId) => {
2249
+ return this.glue.channels.subscribe((data, contextData, updaterId) => {
2328
2250
  if (this.isUpdateFromMe(updaterId) || !contextData || !contextData.latest_fdc3_type) {
2329
2251
  return;
2330
2252
  }
@@ -2335,13 +2257,28 @@ class GlueController {
2335
2257
  didReplay.replayed = true;
2336
2258
  });
2337
2259
  }
2260
+ channelsSubscribe(callback, contextType) {
2261
+ const didReplay = { replayed: false };
2262
+ return this.glue.channels.subscribe((data, contextData, updaterId) => {
2263
+ if (this.isUpdateFromMe(updaterId) || !contextData || !data.fdc3) {
2264
+ return;
2265
+ }
2266
+ if (contextType && data.fdc3.type !== contextType && !didReplay.replayed) {
2267
+ this.invokePreviouslyBroadcastedData({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
2268
+ didReplay.replayed = true;
2269
+ return;
2270
+ }
2271
+ callback(data.fdc3, this.getContextMetadata(updaterId));
2272
+ didReplay.replayed = true;
2273
+ });
2274
+ }
2338
2275
  contextsSubscribe(contextName, callback) {
2339
2276
  const didReplay = { replayed: false };
2340
2277
  return this.glue.contexts.subscribe(contextName, (contextData, addedData, removed, _, extraData) => {
2341
2278
  if (this.isUpdateFromMe(extraData?.updaterId)) {
2342
2279
  return;
2343
2280
  }
2344
- if (!this.checkIfAppChannelShouldInvokeInitialReplay(didReplay, contextData)) {
2281
+ if (!this.checkIfShouldInvokeInitialReplay(didReplay, contextData)) {
2345
2282
  return;
2346
2283
  }
2347
2284
  this.parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata: this.getContextMetadata(extraData?.updaterId) });
@@ -2353,6 +2290,21 @@ class GlueController {
2353
2290
  initSubLogger(name) {
2354
2291
  return this.logger?.subLogger(name);
2355
2292
  }
2293
+ getPrefs(app) {
2294
+ return this.glue.prefs.get(app);
2295
+ }
2296
+ async checkIsFdc3DataWrappingSupported() {
2297
+ const globalBrowserNamespace = window.glue42core || window.iobrowser;
2298
+ const methodName = globalBrowserNamespace ? BrowserClientControlMethodName : DesktopClientControlMethodName;
2299
+ const data = globalBrowserNamespace ? { domain: "system", operation: "isFdc3DataWrappingSupported" } : { command: "isFdc3DataWrappingSupported" };
2300
+ try {
2301
+ const res = await this.glue.interop.invoke(methodName, data, { instance: this.interopInstance().instance });
2302
+ return res.returned.isSupported;
2303
+ }
2304
+ catch (error) {
2305
+ return false;
2306
+ }
2307
+ }
2356
2308
  invokePreviouslyBroadcastedData({ callback, contextData, metadata, contextType }) {
2357
2309
  const invokeForType = contextType || this.channelsParser.mapChannelsDelimiterToFDC3Type(contextData.latest_fdc3_type);
2358
2310
  const dataForContextType = this.getLatestBroadcastedDataByContextType(contextData, invokeForType);
@@ -2407,7 +2359,7 @@ class GlueController {
2407
2359
  });
2408
2360
  return foundData;
2409
2361
  }
2410
- checkIfAppChannelShouldInvokeInitialReplay(didReplay, contextData) {
2362
+ checkIfShouldInvokeInitialReplay(didReplay, contextData) {
2411
2363
  if (!didReplay.replayed) {
2412
2364
  didReplay.replayed = true;
2413
2365
  return false;
@@ -2932,7 +2884,7 @@ class UserChannel {
2932
2884
  return this.channelsController.broadcast(generateCommandId(), context, this.id);
2933
2885
  }
2934
2886
  async getCurrentContext(contextType) {
2935
- nonEmptyStringDecoder.run(contextType);
2887
+ optionalNonEmptyStringDecoder.run(contextType);
2936
2888
  return this.channelsController.getContextForChannel({ commandId: generateCommandId(), channelId: this.id, contextType });
2937
2889
  }
2938
2890
  async addContextListener(contextType, handler) {
@@ -3074,6 +3026,10 @@ class IntentsController {
3074
3026
  this.logger?.info(`[${commandId}] - raiseIntentForContext() invoked with contextType ${context.type} and target ${target}`);
3075
3027
  const filteredHandlersMethodExist = this.glueController.doesFilterHandlersExist();
3076
3028
  const getIntentsMethodExist = this.glueController.doesGetIntentsExist();
3029
+ const rememberedIntentHandlerForContextType = await this.checkForRememberedIntentHandlerForContext(context.type);
3030
+ if (rememberedIntentHandlerForContextType) {
3031
+ return this.invokeRaiseIntent(commandId, { context, intent: rememberedIntentHandlerForContextType.intent });
3032
+ }
3077
3033
  if (!filteredHandlersMethodExist || !getIntentsMethodExist || target) {
3078
3034
  return this.legacyRaiseIntentForContext({ commandId, context, target });
3079
3035
  }
@@ -3103,28 +3059,23 @@ class IntentsController {
3103
3059
  await this.glueController.gluePromise;
3104
3060
  this.logger?.info(`[${commandId}] - addIntentListener() invoked for intent ${intent}`);
3105
3061
  const wrappedHandler = this.getWrappedIntentHandler(handler);
3106
- const myInstance = this.glueController.getMyInteropInstance();
3107
- const myApplication = this.glueController.getApplication(myInstance.applicationName);
3108
- let appConfigIntentDef;
3109
- const globalBrowserNamespace = window.glue42core || window.iobrowser;
3110
- const globalDesktopNamespace = window.glue42gd || window.iodesktop;
3111
- if (globalBrowserNamespace) {
3112
- appConfigIntentDef = myApplication?.userProperties.intents?.find((appIntent) => appIntent.name === intent);
3062
+ return this.glueController.addIntentListener(intent, wrappedHandler);
3063
+ }
3064
+ async checkForRememberedIntentHandlerForContext(contextType) {
3065
+ const prefs = await this.glueController.getPrefs();
3066
+ const intentPrefs = prefs.data?.intents;
3067
+ if (!intentPrefs) {
3068
+ return;
3113
3069
  }
3114
- if (globalDesktopNamespace) {
3115
- const appConfig = await myApplication.getConfiguration();
3116
- appConfigIntentDef = appConfig?.intents?.find((appIntent) => appIntent.name === intent);
3070
+ const prefsForContextType = Object.entries(intentPrefs).find(([intentName, savedValue]) => savedValue.filter?.contextTypes?.includes(contextType));
3071
+ if (!prefsForContextType) {
3072
+ return;
3117
3073
  }
3118
- const intentRequest = {
3074
+ const [intent, rememberedHandlerWithFilter] = prefsForContextType;
3075
+ return {
3119
3076
  intent,
3120
- displayName: appConfigIntentDef?.displayName,
3121
- description: appConfigIntentDef?.description,
3122
- contextTypes: appConfigIntentDef?.contexts || Fdc3SupportedIntentTypes[intent],
3123
- resultType: appConfigIntentDef?.resultType
3077
+ handler: rememberedHandlerWithFilter.handler
3124
3078
  };
3125
- Object.keys(intentRequest)
3126
- .forEach((key) => intentRequest[key] === undefined && delete intentRequest[key]);
3127
- return this.glueController.addIntentListener(intentRequest, wrappedHandler);
3128
3079
  }
3129
3080
  filterGlueIntentHandlers({ commandId, intent, context, target }) {
3130
3081
  let filteredGlueIntent;
@@ -3174,9 +3125,7 @@ class IntentsController {
3174
3125
  return servers;
3175
3126
  }
3176
3127
  filterIntentHandlersByContext(intent, context) {
3177
- const filteredGlueIntent = context.type === fdc3NothingContextType
3178
- ? intent
3179
- : this.getGlueIntentWithFilteredHandlers(intent, { contextType: context.type });
3128
+ const filteredGlueIntent = this.getGlueIntentWithFilteredHandlers(intent, { contextType: context.type });
3180
3129
  if (!filteredGlueIntent.handlers.length) {
3181
3130
  throw { message: ResolveError.NoAppsFound, reason: `There's no app registering an intent with the passed context type ${context.type}` };
3182
3131
  }
@@ -3288,23 +3237,14 @@ class IntentsController {
3288
3237
  }
3289
3238
  getGlueIntentWithFilteredHandlers(glueIntent, filter) {
3290
3239
  const { name, handlers } = glueIntent;
3291
- const desktopGlobal = window.glue42gd || window.iodesktop;
3292
3240
  let filteredHandlers = handlers;
3293
- if (filter.contextType) {
3294
- filteredHandlers = handlers.filter((handler) => {
3295
- if (handler.instanceId) {
3296
- const appExists = desktopGlobal && handler.applicationName === Glue42EnterpriseNoAppWindow
3297
- ? false
3298
- : !!(this.glueController.getApplication(handler.applicationName));
3299
- return appExists
3300
- ? handler.contextTypes?.includes(filter.contextType)
3301
- : handler;
3302
- }
3303
- return handler.contextTypes?.includes(filter.contextType);
3304
- });
3241
+ const contextType = filter.contextType;
3242
+ if (contextType) {
3243
+ filteredHandlers = handlers.filter((handler) => handler.instanceId ? true : handler.contextTypes?.includes(contextType));
3305
3244
  }
3306
- if (filter.resultType) {
3307
- filteredHandlers = handlers.filter((handler) => handler.resultType?.includes(filter.resultType));
3245
+ const resultType = filter.resultType;
3246
+ if (resultType) {
3247
+ filteredHandlers = handlers.filter((handler) => handler.instanceId ? true : handler.resultType?.includes(resultType));
3308
3248
  }
3309
3249
  return { name, handlers: filteredHandlers };
3310
3250
  }
@@ -3344,7 +3284,7 @@ class IntentsController {
3344
3284
  }
3345
3285
  }
3346
3286
 
3347
- var version = "2.3.3";
3287
+ var version = "2.4.0-next.0";
3348
3288
 
3349
3289
  class ApplicationsController {
3350
3290
  glueController;
@@ -3521,454 +3461,119 @@ class ApplicationsController {
3521
3461
  }
3522
3462
  }
3523
3463
 
3524
- class ChannelsController {
3464
+ class EventReceiver {
3525
3465
  glueController;
3526
- channelsStateStore;
3527
- channelsParser;
3528
- channelsFactory;
3529
- glueEventsController;
3530
- _logger;
3531
- initDonePromise;
3532
- invokeContextHandlerWithStartupContext = true;
3533
- constructor(glueController, channelsStateStore, channelsParser, channelsFactory, glueEventsController) {
3466
+ eventDispatcher;
3467
+ glueResponseReceived = false;
3468
+ glueInitialized = false;
3469
+ _glueReceiverHandler;
3470
+ events = {
3471
+ "start": { name: START, handle: this.handleStart.bind(this) },
3472
+ "requestGlueResponse": { name: REQUEST_GLUE_RESPONSE, handle: this.handleRequestGlueResponse.bind(this) }
3473
+ };
3474
+ constructor(glueController, eventDispatcher) {
3534
3475
  this.glueController = glueController;
3535
- this.channelsStateStore = channelsStateStore;
3536
- this.channelsParser = channelsParser;
3537
- this.channelsFactory = channelsFactory;
3538
- this.glueEventsController = glueEventsController;
3539
- this.initDonePromise = this.initialize();
3540
- this.initDonePromise.catch((err) => {
3541
- this.logger?.error(err);
3542
- });
3543
- }
3544
- async getStartupContext() {
3545
- await this.initDonePromise;
3546
- const fdc3StartupContext = await this.glueController.getMyWindowContext();
3547
- return fdc3StartupContext?.fdc3?.context?.payload || null;
3476
+ this.eventDispatcher = eventDispatcher;
3548
3477
  }
3549
- async addContextListener({ commandId, handler, contextType, channelId }) {
3550
- await this.initDonePromise;
3551
- this.logger?.info(`[${commandId}] - addContextListener() invoked for contextType ${contextType} and channelId ${channelId}`);
3552
- if (this.invokeContextHandlerWithStartupContext && !channelId) {
3553
- this.logger?.info(`[${commandId}] - trying to invoke context handler with window context`);
3554
- this.handleWindowContextOnOpening(commandId, handler, contextType).catch((err) => this.logger?.warn(`[${commandId}] - ${err}`));
3555
- }
3556
- const channelIdToSubscribeTo = channelId || this.channelsStateStore.currentChannel?.id;
3557
- return this.addContextListenerByChannelId({ commandId, handler, invokedOnChannelModel: !!channelId, channelId: channelIdToSubscribeTo, contextType });
3478
+ start() {
3479
+ this.wireCustomEventListener();
3480
+ this.eventDispatcher.fireNotifyStarted();
3558
3481
  }
3559
- async broadcast(commandId, context, channelId) {
3560
- await this.initDonePromise;
3561
- this.logger?.info(`[${commandId}] - broadcast() invoked with contextType ${context.type} and channelId ${channelId}`);
3562
- const canBroadcast = this.isBroadcastPermitted(commandId, channelId);
3563
- if (!canBroadcast) {
3564
- return;
3565
- }
3566
- const channelIdToBroadcastTo = channelId || this.channelsStateStore.currentChannel.id;
3567
- return this.broadcastByChannelId(commandId, channelIdToBroadcastTo, context);
3482
+ wireCustomEventListener() {
3483
+ this._glueReceiverHandler = this.glueReceiverHandler.bind(this);
3484
+ window.addEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
3568
3485
  }
3569
- async getUserChannels(commandId) {
3570
- await this.initDonePromise;
3571
- this.logger?.info(`[${commandId}] - getUserChannels() invoked`);
3572
- return Object.values(this.channelsStateStore.userChannels);
3486
+ handleStart() {
3487
+ this.eventDispatcher.fireRequestGlue();
3573
3488
  }
3574
- async getOrCreateChannel({ commandId, channelId }) {
3575
- await this.initDonePromise;
3576
- this.logger?.info(`[${commandId}] - getOrCreateChannel() invoked for channel with id ${channelId}`);
3577
- const isUserChannel = this.isUserChannel(channelId);
3578
- if (isUserChannel) {
3579
- throw { message: ChannelError.AccessDenied, reason: "There's an already existing system channel with passed id. Retrieve it using fdc3.getSystemChannels() or create a new app channel with a different id" };
3489
+ glueReceiverHandler(event) {
3490
+ const data = event.detail;
3491
+ if (!data || !data.glue42) {
3492
+ return;
3580
3493
  }
3581
- const isPrivateChannel = this.channelsStateStore.getPrivateChannelById(channelId);
3582
- if (isPrivateChannel) {
3583
- throw { message: ChannelError.AccessDenied, reason: "Cannot retrieve a private channel" };
3494
+ const glue42Event = data.glue42.event;
3495
+ const foundHandler = this.events[glue42Event];
3496
+ if (!foundHandler) {
3497
+ return;
3584
3498
  }
3585
- return this.getOrCreateAppChannel(commandId, channelId);
3499
+ foundHandler.handle(data.glue42.message);
3586
3500
  }
3587
- async joinUserChannel({ commandId, channelId }) {
3588
- await this.initDonePromise;
3589
- this.logger?.info(`[${commandId}] - joinUserChannel() invoked for channel with id ${channelId}`);
3590
- const isAppChannel = this.doesAppChannelExist(channelId);
3591
- if (isAppChannel) {
3592
- throw { message: ChannelError.AccessDenied, reason: "Cannot join an app channel" };
3593
- }
3594
- const channelToJoin = this.channelsStateStore.userChannels[channelId];
3595
- if (!channelToJoin) {
3596
- throw { message: ChannelError.NoChannelFound, reason: `Cannot find user channel with id ${channelId}` };
3501
+ async handleRequestGlueResponse(data) {
3502
+ if (this.glueResponseReceived && this.glueInitialized) {
3503
+ return;
3597
3504
  }
3598
- const glueChannelName = this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId);
3599
- this.channelsStateStore.currentChannel = channelToJoin;
3600
- this.logger?.info(`[${commandId}] - joining fdc3 user channel with id ${channelId} (underlying glue channel: ${glueChannelName})`);
3601
- await this.glueController.joinChannel(glueChannelName);
3602
- }
3603
- async getCurrentChannel(commandId) {
3604
- await this.initDonePromise;
3605
- this.logger?.info(`[${commandId}] - getCurrentChannel() invoked`);
3606
- return this.channelsStateStore.currentChannel;
3607
- }
3608
- async leaveCurrentChannel(commandId) {
3609
- await this.initDonePromise;
3610
- this.logger?.info(`[${commandId}] - leaveCurrentChannel() invoked`);
3611
- if (!this.channelsStateStore.currentChannel) {
3612
- this.logger?.info(`[${commandId}] - no channel to leave`);
3505
+ this.glueResponseReceived = true;
3506
+ const { glue } = data;
3507
+ const glueValidator = this.glueController.validateGlue(glue);
3508
+ if (!glueValidator.isValid) {
3509
+ this.glueController.initializeFailed(glueValidator.error);
3510
+ window.removeEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
3613
3511
  return;
3614
3512
  }
3615
- await this.glueController.leaveChannel();
3616
- this.channelsStateStore.currentChannel = null;
3617
- this.logger?.info(`[${commandId}] - current channel is left. unsubscribing from all listeners`);
3618
- }
3619
- async getContextForChannel({ commandId, channelId, contextType }) {
3620
- await this.initDonePromise;
3621
- this.logger?.info(`[${commandId}] - getContextForChannel() invoked for channel with id ${channelId}`);
3622
- const isUserChannel = this.isUserChannel(channelId);
3623
- if (!contextType) {
3624
- this.logger?.info(`[${commandId}] - retrieving latest context broadcasted on channel with id ${channelId}`);
3625
- let context;
3626
- if (isUserChannel) {
3627
- const glueChannelName = this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId);
3628
- const glueChannelWithPrefix = this.channelsParser.mapChannelNameToContextName(glueChannelName);
3629
- this.logger?.info(`[${commandId}] - getting context for user channel with id ${channelId} (underlying glue channel ${glueChannelName})`);
3630
- context = await this.glueController.getContext(glueChannelWithPrefix);
3631
- }
3632
- else {
3633
- this.logger?.info(`[${commandId}] - getting context for app channel with id ${channelId}`);
3634
- context = await this.glueController.getContext(channelId);
3635
- }
3636
- return context.latest_fdc3_type
3637
- ? this.channelsParser.parseContextsDataToInitialFDC3Data(context)
3638
- : null;
3639
- }
3640
- this.logger?.info(`[${commandId}] Retrieving latest context of type ${contextType} broadcasted on ${isUserChannel ? "user" : "app"} channel with id ${channelId}`);
3641
- const parsedType = this.channelsParser.mapFDC3TypeToChannelsDelimiter(contextType);
3642
- const { data } = isUserChannel
3643
- ? await this.glueController.getChannel(this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId))
3644
- : await this.glueController.getContext(channelId);
3645
- return data && data[`fdc3_${parsedType}`]
3646
- ? this.channelsParser.parseContextsDataToInitialFDC3Data({ data, latest_fdc3_type: parsedType })
3647
- : null;
3513
+ window.removeEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
3514
+ this.glueController.initialize(glue);
3515
+ this.eventDispatcher.fireFdc3Ready();
3516
+ this.glueInitialized = true;
3648
3517
  }
3649
- async createPrivateChannel(commandId) {
3650
- await this.initDonePromise;
3651
- this.logger?.info(`[${commandId}] - createPrivateChannel() invoked`);
3652
- const channelId = `${PrivateChannelPrefix}${nanoid()}`;
3653
- await this.glueEventsController.initializeCollaborateMethod();
3654
- const pc = this.buildPrivateChannel(channelId, commandId, true);
3655
- return pc.toApi();
3518
+ }
3519
+
3520
+ class ChannelsStateStore {
3521
+ _currentChannel = null;
3522
+ _userChannels = {};
3523
+ _fdc3ChannelIdsToGlueChannelNames = {};
3524
+ _privateChannels = {};
3525
+ get currentChannel() {
3526
+ return this._currentChannel;
3656
3527
  }
3657
- async removePrivateChannelFromStoreById(id) {
3658
- this.channelsStateStore.removePrivateChannelById(id);
3528
+ set currentChannel(newChannelValue) {
3529
+ this._currentChannel = newChannelValue;
3659
3530
  }
3660
- async invokeSystemMethod(args, target) {
3661
- if (!target) {
3662
- return;
3663
- }
3664
- return this.glueController.invokeSystemMethod(args, target);
3531
+ get userChannels() {
3532
+ return this._userChannels;
3665
3533
  }
3666
- getMyServerInstance() {
3667
- return this.glueController.getMyInteropInstance();
3534
+ addUserChannel(channel) {
3535
+ this._userChannels[channel.id] = channel;
3668
3536
  }
3669
- async addClientToPrivateChannel(commandId, channelId, clientId) {
3670
- this.logger?.info(`[${commandId}] - client with id ${clientId} added to private channel with id ${channelId}`);
3671
- await this.glueController.updateContext(channelId, { clientId });
3537
+ addFdc3IdToGlueChannelName(fdc3Id, glueChannelName) {
3538
+ this._fdc3ChannelIdsToGlueChannelNames[fdc3Id] = glueChannelName;
3672
3539
  }
3673
- async isPrivateChannelDisconnected({ commandId, channelId }) {
3674
- this.logger?.info(`[${commandId}] - checking if private channel with id ${channelId} is disconnected`);
3675
- const context = await this.glueController.getContext(channelId);
3676
- return !!context.disconnected;
3540
+ getGlueChannelNameByFdc3ChannelId(fdc3Id) {
3541
+ return this._fdc3ChannelIdsToGlueChannelNames[fdc3Id];
3677
3542
  }
3678
- subscribeOnInstanceStop(channelId, handler, commandId) {
3679
- this.logger?.info(`[${commandId}] - subscribing onInstanceStopped callback for channel with id ${channelId}`);
3680
- return this.glueController.registerOnInstanceStopped(handler.bind(this));
3543
+ getFdc3ChannelIdByGlueChannelName(glueChannelName) {
3544
+ const [key] = Object.entries(this._fdc3ChannelIdsToGlueChannelNames).find(([_, value]) => value === glueChannelName);
3545
+ return key;
3681
3546
  }
3682
- buildPrivateChannel(channelId, commandId, isCreator) {
3683
- const logger = this.glueController.initSubLogger(channelId);
3684
- const channel = this.buildChannel(ChannelTypes.Private, { id: channelId, logger, isCreator });
3685
- this.logger?.info(`[${commandId}] - private channel with id ${channelId} created. Adding it to the store`);
3686
- this.channelsStateStore.addPrivateChannel(channel);
3687
- return channel;
3547
+ addPrivateChannel(privateChannel) {
3548
+ this._privateChannels[privateChannel.id] = privateChannel;
3688
3549
  }
3689
- get logger() {
3690
- if (!this._logger) {
3691
- this._logger = this.glueController.initSubLogger("fdc3.channels.controller");
3692
- }
3693
- return this._logger;
3550
+ getPrivateChannelById(id) {
3551
+ return this._privateChannels[id];
3694
3552
  }
3695
- async initialize() {
3696
- await this.glueController.gluePromise;
3697
- const current = this.glueController.getCurrentChannel();
3698
- const glueChannels = await this.glueController.listAllChannels();
3699
- const glueChannelsWithFdc3Meta = glueChannels.filter((glueChannel) => glueChannel.meta.fdc3);
3700
- glueChannelsWithFdc3Meta.forEach((glueChannel) => {
3701
- const userChannel = this.buildChannel(ChannelTypes.User, { displayMetadata: { glueChannel } });
3702
- this.channelsStateStore.addFdc3IdToGlueChannelName(userChannel.id, glueChannel.name);
3703
- this.channelsStateStore.addUserChannel(userChannel);
3704
- if (current && glueChannel.name === current) {
3705
- this.channelsStateStore.currentChannel = userChannel;
3706
- }
3707
- });
3708
- this.glueController.setOnChannelChanged(this.handleOnChannelChanged.bind(this));
3553
+ removePrivateChannelById(id) {
3554
+ delete this._privateChannels[id];
3709
3555
  }
3710
- async handleOnChannelChanged(channelId) {
3711
- if (!channelId) {
3712
- return;
3713
- }
3714
- const isFdc3ChannelName = fdc3ChannelNames.includes(channelId);
3715
- const userChannelId = isFdc3ChannelName ? channelId : this.channelsStateStore.getFdc3ChannelIdByGlueChannelName(channelId);
3716
- this.channelsStateStore.currentChannel = this.channelsStateStore.userChannels[userChannelId];
3556
+ }
3557
+
3558
+ function getDefaultExportFromCjs (x) {
3559
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
3560
+ }
3561
+
3562
+ function createRegistry(options) {
3563
+ if (options && options.errorHandling
3564
+ && typeof options.errorHandling !== "function"
3565
+ && options.errorHandling !== "log"
3566
+ && options.errorHandling !== "silent"
3567
+ && options.errorHandling !== "throw") {
3568
+ throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed");
3717
3569
  }
3718
- isBroadcastPermitted(commandId, channelId) {
3719
- if (channelId) {
3720
- return true;
3721
- }
3722
- if (!this.channelsStateStore.currentChannel) {
3723
- this.logger?.info(`[${commandId}] - invocation of broadcast ignored - no channel to broadcast to`);
3724
- console.error("You need to join a user channel in order to broadcast");
3725
- return false;
3726
- }
3727
- if (this.channelsStateStore.currentChannel.type === ChannelTypes.App) {
3728
- this.logger?.info(`[${commandId}] - invocation of broadcast ignored - cannot broadcast on app channel directly`);
3729
- console.error("You can't broadcast to an app channel directly - use channel's broadcast method instead");
3730
- return false;
3731
- }
3732
- return true;
3733
- }
3734
- async handleWindowContextOnOpening(commandId, handler, contextType) {
3735
- const myWindow = this.glueController.getMyWindow();
3736
- if (!myWindow) {
3737
- this.logger?.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
3738
- this.invokeContextHandlerWithStartupContext = false;
3739
- return;
3740
- }
3741
- const windowContext = await myWindow.getContext();
3742
- if (!windowContext) {
3743
- this.logger?.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
3744
- this.invokeContextHandlerWithStartupContext = false;
3745
- return;
3746
- }
3747
- if (!isValidNonEmptyObject(windowContext) || !windowContext.fdc3) {
3748
- this.logger?.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
3749
- this.invokeContextHandlerWithStartupContext = false;
3750
- return;
3751
- }
3752
- await this.glueEventsController.initializeCollaborateMethod();
3753
- FDC3StartupContextDecoder.runWithException(windowContext);
3754
- const { fdc3 } = windowContext;
3755
- this.logger?.trace(`[${commandId}] - received FDC3 startup context from ${JSON.stringify(fdc3.openApp)} for contextType ${fdc3.context.contextType}`);
3756
- const isSameContextType = contextType ? fdc3.context.contextType === contextType : true;
3757
- if (!isSameContextType) {
3758
- this.logger?.info(`[${commandId}] - addContextListener handler won't be invoked for contextType ${contextType} for startup context with type: ${fdc3.context.contextType}`);
3759
- return;
3760
- }
3761
- this.logger?.info(`[${commandId}] - invoking addContextListener handler with startup context with type ${fdc3.context.contextType}`);
3762
- try {
3763
- handler(fdc3.context.payload, { source: fdc3.openApp });
3764
- }
3765
- catch (error) {
3766
- this.logger?.error(typeof error === "string" ? error : error.message ? JSON.stringify(error.message) : JSON.stringify(error));
3767
- }
3768
- this.invokeContextHandlerWithStartupContext = false;
3769
- this.logger?.trace(`[${commandId}] - invoking response method to with target ${JSON.stringify(fdc3.openApp)}`);
3770
- await this.invokeSystemMethod({ action: "startupContextOpened", correlationId: fdc3.collaborationId }, fdc3.openApp.instanceId);
3771
- this.logger?.trace(`[${commandId}] - system method invocation success for 'startupContextOpened' heard`);
3772
- }
3773
- async getOrCreateAppChannel(commandId, channelId) {
3774
- const exists = this.doesAppChannelExist(channelId);
3775
- if (!exists) {
3776
- this.logger?.info(`[${commandId}] - app channel with id ${channelId} does not exist. Creating one`);
3777
- await this.glueController.updateContext(channelId, {});
3778
- }
3779
- this.logger?.info(`[${commandId}] - returning app channel with id ${channelId}`);
3780
- const logger = this.glueController.initSubLogger(`app.channel.${channelId}`);
3781
- return this.buildChannel(ChannelTypes.App, { id: channelId, logger });
3782
- }
3783
- doesAppChannelExist(name) {
3784
- return !name.includes(PrivateChannelPrefix) && this.glueController.getAllContexts().some((ctxName) => ctxName === name);
3785
- }
3786
- isUserChannel(channelId) {
3787
- if (!channelId) {
3788
- return false;
3789
- }
3790
- return !!this.channelsStateStore.userChannels[channelId];
3791
- }
3792
- async broadcastByChannelId(commandId, channelId, context) {
3793
- const isUserChannel = this.isUserChannel(channelId);
3794
- if (!isUserChannel) {
3795
- this.logger?.info(`[${commandId}] - broadcasting on app channel with id ${channelId}`);
3796
- return this.glueController.updateContextWithLatestFdc3Type(channelId, context);
3797
- }
3798
- const glueChannelName = this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId);
3799
- this.logger?.info(`[${commandId}] - broadcasting on fdc3 user channel with id ${channelId} (underlying glue channel: ${glueChannelName})`);
3800
- return this.glueController.channelsUpdate(glueChannelName, context);
3801
- }
3802
- async addContextListenerByChannelId({ commandId, channelId, handler, contextType, invokedOnChannelModel }) {
3803
- const subHandler = parseContextHandler(handler, contextType);
3804
- if (!channelId) {
3805
- this.logger?.info(`[${commandId}] - Creating a channel subscription using glue.channels.subscribe`);
3806
- const unsubscribe = this.glueController.channelsSubscribe(subHandler, contextType);
3807
- return { unsubscribe };
3808
- }
3809
- const channelType = this.getChannelTypeById(channelId);
3810
- if (channelType === ChannelTypes.User) {
3811
- return this.addContextListenerOnUserChannel({ commandId, channelId, handler: subHandler, contextType, invokedOnChannelModel });
3812
- }
3813
- if (channelType === ChannelTypes.App) {
3814
- this.logger?.info(`[${commandId}] - subscribing for fdc3 app channel with id ${channelId} (underlying glue context with same name)`);
3815
- const unsubscribe = await this.glueController.contextsSubscribe(channelId, subHandler);
3816
- return {
3817
- unsubscribe: () => {
3818
- this.logger?.info(`[${commandId}] - invoking unsubscribe for app channel with id ${channelId}`);
3819
- unsubscribe();
3820
- }
3821
- };
3822
- }
3823
- throw { message: ChannelError.AccessDenied, reason: "Cannot add a context listener on an invalid channel" };
3824
- }
3825
- async addContextListenerOnUserChannel({ commandId, channelId, handler, invokedOnChannelModel, contextType }) {
3826
- let unsubscribe;
3827
- if (invokedOnChannelModel) {
3828
- const contextToSubscribeTo = this.channelsParser.mapChannelNameToContextName(this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId));
3829
- this.logger?.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
3830
- unsubscribe = await this.glueController.contextsSubscribe(contextToSubscribeTo, handler);
3831
- }
3832
- else {
3833
- this.logger?.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
3834
- unsubscribe = this.glueController.channelsSubscribe(handler, contextType);
3835
- }
3836
- return {
3837
- unsubscribe: () => {
3838
- this.logger?.info(`[${commandId}] - invoking unsubscribe for fdc3 user channel with id ${channelId}`);
3839
- unsubscribe();
3840
- }
3841
- };
3842
- }
3843
- getChannelTypeById(channelId) {
3844
- const isUser = this.isUserChannel(channelId);
3845
- if (isUser) {
3846
- return ChannelTypes.User;
3847
- }
3848
- const isApp = this.doesAppChannelExist(channelId);
3849
- if (isApp) {
3850
- return ChannelTypes.App;
3851
- }
3852
- throw { message: ChannelError.NoChannelFound, reason: `Channel with id: ${channelId} does not exist` };
3853
- }
3854
- buildChannel(type, data) {
3855
- return this.channelsFactory.buildModel({ type, ...data });
3856
- }
3857
- }
3858
-
3859
- class EventReceiver {
3860
- glueController;
3861
- eventDispatcher;
3862
- glueResponseReceived = false;
3863
- glueInitialized = false;
3864
- _glueReceiverHandler;
3865
- events = {
3866
- "start": { name: START, handle: this.handleStart.bind(this) },
3867
- "requestGlueResponse": { name: REQUEST_GLUE_RESPONSE, handle: this.handleRequestGlueResponse.bind(this) }
3868
- };
3869
- constructor(glueController, eventDispatcher) {
3870
- this.glueController = glueController;
3871
- this.eventDispatcher = eventDispatcher;
3872
- }
3873
- start() {
3874
- this.wireCustomEventListener();
3875
- this.eventDispatcher.fireNotifyStarted();
3876
- }
3877
- wireCustomEventListener() {
3878
- this._glueReceiverHandler = this.glueReceiverHandler.bind(this);
3879
- window.addEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
3880
- }
3881
- handleStart() {
3882
- this.eventDispatcher.fireRequestGlue();
3883
- }
3884
- glueReceiverHandler(event) {
3885
- const data = event.detail;
3886
- if (!data || !data.glue42) {
3887
- return;
3888
- }
3889
- const glue42Event = data.glue42.event;
3890
- const foundHandler = this.events[glue42Event];
3891
- if (!foundHandler) {
3892
- return;
3893
- }
3894
- foundHandler.handle(data.glue42.message);
3895
- }
3896
- async handleRequestGlueResponse(data) {
3897
- if (this.glueResponseReceived && this.glueInitialized) {
3898
- return;
3899
- }
3900
- this.glueResponseReceived = true;
3901
- const { glue } = data;
3902
- const glueValidator = this.glueController.validateGlue(glue);
3903
- if (!glueValidator.isValid) {
3904
- this.glueController.initializeFailed(glueValidator.error);
3905
- window.removeEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
3906
- return;
3907
- }
3908
- window.removeEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
3909
- this.glueController.initialize(glue);
3910
- this.eventDispatcher.fireFdc3Ready();
3911
- this.glueInitialized = true;
3912
- }
3913
- }
3914
-
3915
- class ChannelsStateStore {
3916
- _currentChannel = null;
3917
- _userChannels = {};
3918
- _fdc3ChannelIdsToGlueChannelNames = {};
3919
- _privateChannels = {};
3920
- get currentChannel() {
3921
- return this._currentChannel;
3922
- }
3923
- set currentChannel(newChannelValue) {
3924
- this._currentChannel = newChannelValue;
3925
- }
3926
- get userChannels() {
3927
- return this._userChannels;
3928
- }
3929
- addUserChannel(channel) {
3930
- this._userChannels[channel.id] = channel;
3931
- }
3932
- addFdc3IdToGlueChannelName(fdc3Id, glueChannelName) {
3933
- this._fdc3ChannelIdsToGlueChannelNames[fdc3Id] = glueChannelName;
3934
- }
3935
- getGlueChannelNameByFdc3ChannelId(fdc3Id) {
3936
- return this._fdc3ChannelIdsToGlueChannelNames[fdc3Id];
3937
- }
3938
- getFdc3ChannelIdByGlueChannelName(glueChannelName) {
3939
- const [key] = Object.entries(this._fdc3ChannelIdsToGlueChannelNames).find(([_, value]) => value === glueChannelName);
3940
- return key;
3941
- }
3942
- addPrivateChannel(privateChannel) {
3943
- this._privateChannels[privateChannel.id] = privateChannel;
3944
- }
3945
- getPrivateChannelById(id) {
3946
- return this._privateChannels[id];
3947
- }
3948
- removePrivateChannelById(id) {
3949
- delete this._privateChannels[id];
3950
- }
3951
- }
3952
-
3953
- function getDefaultExportFromCjs (x) {
3954
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
3955
- }
3956
-
3957
- function createRegistry(options) {
3958
- if (options && options.errorHandling
3959
- && typeof options.errorHandling !== "function"
3960
- && options.errorHandling !== "log"
3961
- && options.errorHandling !== "silent"
3962
- && options.errorHandling !== "throw") {
3963
- throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed");
3964
- }
3965
- var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling;
3966
- var callbacks = {};
3967
- function add(key, callback, replayArgumentsArr) {
3968
- var callbacksForKey = callbacks[key];
3969
- if (!callbacksForKey) {
3970
- callbacksForKey = [];
3971
- callbacks[key] = callbacksForKey;
3570
+ var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling;
3571
+ var callbacks = {};
3572
+ function add(key, callback, replayArgumentsArr) {
3573
+ var callbacksForKey = callbacks[key];
3574
+ if (!callbacksForKey) {
3575
+ callbacksForKey = [];
3576
+ callbacks[key] = callbacksForKey;
3972
3577
  }
3973
3578
  callbacksForKey.push(callback);
3974
3579
  if (replayArgumentsArr) {
@@ -4519,28 +4124,451 @@ class ApplicationsStateStore {
4519
4124
  }
4520
4125
  }
4521
4126
 
4522
- class IoC {
4523
- _eventDispatcher;
4524
- _eventReceiver;
4525
- _desktopAgent;
4526
- _glueController;
4527
- _intentsController;
4528
- _applicationController;
4529
- _channelsController;
4530
- _channelsParser;
4531
- _channelsStateStore;
4532
- _channelsFactory;
4533
- _fdc3;
4534
- _eventsController;
4535
- _applicationsStateStore;
4536
- get ioc() {
4537
- return this;
4538
- }
4539
- get eventReceiver() {
4540
- if (!this._eventReceiver) {
4541
- this._eventReceiver = new EventReceiver(this.glueController, this.eventDispatcher);
4542
- }
4543
- return this._eventReceiver;
4127
+ class ChannelsBaseController {
4128
+ glueController;
4129
+ stateStore;
4130
+ parser;
4131
+ channelsFactory;
4132
+ glueEventsController;
4133
+ legacyController;
4134
+ ioFdc3SupportedController;
4135
+ _logger;
4136
+ initDonePromise;
4137
+ invokeContextHandlerWithStartupContext = true;
4138
+ isFdc3DataWrappingSupported;
4139
+ constructor(glueController, stateStore, parser, channelsFactory, glueEventsController, legacyController, ioFdc3SupportedController) {
4140
+ this.glueController = glueController;
4141
+ this.stateStore = stateStore;
4142
+ this.parser = parser;
4143
+ this.channelsFactory = channelsFactory;
4144
+ this.glueEventsController = glueEventsController;
4145
+ this.legacyController = legacyController;
4146
+ this.ioFdc3SupportedController = ioFdc3SupportedController;
4147
+ this.initDonePromise = this.initialize();
4148
+ this.initDonePromise.catch((err) => {
4149
+ this.logger?.error(err);
4150
+ });
4151
+ }
4152
+ async getStartupContext() {
4153
+ await this.initDonePromise;
4154
+ const fdc3StartupContext = await this.glueController.getMyWindowContext();
4155
+ return fdc3StartupContext?.fdc3?.context?.payload || null;
4156
+ }
4157
+ async addContextListener({ commandId, handler, contextType, channelId }) {
4158
+ await this.initDonePromise;
4159
+ this.logger?.info(`[${commandId}] - addContextListener() invoked for contextType ${contextType} and channelId ${channelId}`);
4160
+ if (this.invokeContextHandlerWithStartupContext && !channelId) {
4161
+ this.logger?.info(`[${commandId}] - trying to invoke context handler with window context`);
4162
+ this.handleWindowContextOnOpening(commandId, handler, contextType).catch((err) => this.logger?.warn(`[${commandId}] - ${err}`));
4163
+ }
4164
+ const channelIdToSubscribeTo = channelId || this.stateStore.currentChannel?.id;
4165
+ if (!channelIdToSubscribeTo) {
4166
+ return this.addContextListenerWithoutChannelId({ commandId, handler, invokedOnChannelModel: !!channelId, contextType });
4167
+ }
4168
+ return this.addContextListenerByChannelId({ commandId, handler, invokedOnChannelModel: !!channelId, channelId: channelIdToSubscribeTo, contextType });
4169
+ }
4170
+ async broadcast(commandId, context, channelId) {
4171
+ await this.initDonePromise;
4172
+ this.logger?.info(`[${commandId}] - broadcast() invoked with contextType ${context.type} and channelId ${channelId}`);
4173
+ const canBroadcast = this.isBroadcastPermitted(commandId, channelId);
4174
+ if (!canBroadcast) {
4175
+ return;
4176
+ }
4177
+ const channelIdToBroadcastTo = channelId || this.stateStore.currentChannel.id;
4178
+ return this.broadcastByChannelId(commandId, channelIdToBroadcastTo, context);
4179
+ }
4180
+ async getUserChannels(commandId) {
4181
+ await this.initDonePromise;
4182
+ this.logger?.info(`[${commandId}] - getUserChannels() invoked`);
4183
+ return Object.values(this.stateStore.userChannels);
4184
+ }
4185
+ async getOrCreateChannel({ commandId, channelId }) {
4186
+ await this.initDonePromise;
4187
+ this.logger?.info(`[${commandId}] - getOrCreateChannel() invoked for channel with id ${channelId}`);
4188
+ const isUserChannel = this.isUserChannel(channelId);
4189
+ if (isUserChannel) {
4190
+ this.logger?.error("There's an already existing system channel with passed id. Retrieve it using fdc3.getSystemChannels() or create a new app channel with a different id");
4191
+ throw new Error(ChannelError.AccessDenied);
4192
+ }
4193
+ const isPrivateChannel = this.stateStore.getPrivateChannelById(channelId);
4194
+ if (isPrivateChannel) {
4195
+ this.logger?.error("Cannot retrieve a private channel");
4196
+ throw new Error(ChannelError.AccessDenied);
4197
+ }
4198
+ return this.getOrCreateAppChannel(commandId, channelId);
4199
+ }
4200
+ async joinUserChannel({ commandId, channelId }) {
4201
+ await this.initDonePromise;
4202
+ this.logger?.info(`[${commandId}] - joinUserChannel() invoked for channel with id ${channelId}`);
4203
+ const isAppChannel = this.doesAppChannelExist(channelId);
4204
+ if (isAppChannel) {
4205
+ this.logger?.error("Cannot join an app channel");
4206
+ throw new Error(ChannelError.AccessDenied);
4207
+ }
4208
+ const channelToJoin = this.stateStore.userChannels[channelId];
4209
+ if (!channelToJoin) {
4210
+ this.logger?.error(`Cannot find user channel with id ${channelId}`);
4211
+ throw new Error(ChannelError.NoChannelFound);
4212
+ }
4213
+ const glueChannelName = this.stateStore.getGlueChannelNameByFdc3ChannelId(channelId);
4214
+ this.stateStore.currentChannel = channelToJoin;
4215
+ this.logger?.info(`[${commandId}] - joining fdc3 user channel with id ${channelId} (underlying glue channel: ${glueChannelName})`);
4216
+ await this.glueController.joinChannel(glueChannelName);
4217
+ }
4218
+ async getCurrentChannel(commandId) {
4219
+ await this.initDonePromise;
4220
+ this.logger?.info(`[${commandId}] - getCurrentChannel() invoked`);
4221
+ return this.stateStore.currentChannel;
4222
+ }
4223
+ async leaveCurrentChannel(commandId) {
4224
+ await this.initDonePromise;
4225
+ this.logger?.info(`[${commandId}] - leaveCurrentChannel() invoked`);
4226
+ if (!this.stateStore.currentChannel) {
4227
+ this.logger?.info(`[${commandId}] - no channel to leave`);
4228
+ return;
4229
+ }
4230
+ await this.glueController.leaveChannel();
4231
+ this.stateStore.currentChannel = null;
4232
+ this.logger?.info(`[${commandId}] - current channel is left. unsubscribing from all listeners`);
4233
+ }
4234
+ async getContextForChannel({ commandId, channelId, contextType }) {
4235
+ await this.initDonePromise;
4236
+ this.logger?.info(`[${commandId}] - getContextForChannel() invoked for channel with id ${channelId}`);
4237
+ const isUserChannel = this.isUserChannel(channelId);
4238
+ if (isUserChannel) {
4239
+ return this.userChannelsSupportController.getContext({ commandId, channelId, contextType });
4240
+ }
4241
+ if (!contextType) {
4242
+ const context = await this.glueController.getContext(channelId);
4243
+ return context.latest_fdc3_type ? this.parser.parseContextsDataToInitialFDC3Data(context) : null;
4244
+ }
4245
+ const parsedType = this.parser.mapFDC3TypeToChannelsDelimiter(contextType);
4246
+ const { data } = await this.glueController.getContext(channelId);
4247
+ return data?.[`fdc3_${parsedType}`]
4248
+ ? this.parser.parseContextsDataToInitialFDC3Data({ data, latest_fdc3_type: parsedType })
4249
+ : null;
4250
+ }
4251
+ async createPrivateChannel(commandId) {
4252
+ await this.initDonePromise;
4253
+ this.logger?.info(`[${commandId}] - createPrivateChannel() invoked`);
4254
+ const channelId = `${PrivateChannelPrefix}${nanoid()}`;
4255
+ await this.glueEventsController.initializeCollaborateMethod();
4256
+ const pc = this.buildPrivateChannel(channelId, commandId, true);
4257
+ return pc.toApi();
4258
+ }
4259
+ async removePrivateChannelFromStoreById(id) {
4260
+ this.stateStore.removePrivateChannelById(id);
4261
+ }
4262
+ async invokeSystemMethod(args, target) {
4263
+ if (!target) {
4264
+ return;
4265
+ }
4266
+ return this.glueController.invokeSystemMethod(args, target);
4267
+ }
4268
+ getMyServerInstance() {
4269
+ return this.glueController.getMyInteropInstance();
4270
+ }
4271
+ async addClientToPrivateChannel(commandId, channelId, clientId) {
4272
+ this.logger?.info(`[${commandId}] - client with id ${clientId} added to private channel with id ${channelId}`);
4273
+ await this.glueController.updateContext(channelId, { clientId });
4274
+ }
4275
+ async isPrivateChannelDisconnected({ commandId, channelId }) {
4276
+ this.logger?.info(`[${commandId}] - checking if private channel with id ${channelId} is disconnected`);
4277
+ const context = await this.glueController.getContext(channelId);
4278
+ return !!context.disconnected;
4279
+ }
4280
+ subscribeOnInstanceStop(channelId, handler, commandId) {
4281
+ this.logger?.info(`[${commandId}] - subscribing onInstanceStopped callback for channel with id ${channelId}`);
4282
+ return this.glueController.registerOnInstanceStopped(handler.bind(this));
4283
+ }
4284
+ buildPrivateChannel(channelId, commandId, isCreator) {
4285
+ const logger = this.glueController.initSubLogger(channelId);
4286
+ const channel = this.buildChannel(ChannelTypes.Private, { id: channelId, logger, isCreator });
4287
+ this.logger?.info(`[${commandId}] - private channel with id ${channelId} created. Adding it to the store`);
4288
+ this.stateStore.addPrivateChannel(channel);
4289
+ return channel;
4290
+ }
4291
+ buildChannel(type, data) {
4292
+ return this.channelsFactory.buildModel({ type, ...data });
4293
+ }
4294
+ get logger() {
4295
+ if (!this._logger) {
4296
+ this._logger = this.glueController.initSubLogger("fdc3.channels.controller");
4297
+ }
4298
+ return this._logger;
4299
+ }
4300
+ get userChannelsSupportController() {
4301
+ return this.isFdc3DataWrappingSupported ? this.ioFdc3SupportedController : this.legacyController;
4302
+ }
4303
+ async initialize() {
4304
+ await this.glueController.gluePromise;
4305
+ this.isFdc3DataWrappingSupported = await this.glueController.checkIsFdc3DataWrappingSupported();
4306
+ const current = this.glueController.getCurrentChannel();
4307
+ const glueChannels = await this.glueController.listAllChannels();
4308
+ const glueChannelsWithFdc3Meta = glueChannels.filter((glueChannel) => glueChannel.meta.fdc3);
4309
+ glueChannelsWithFdc3Meta.forEach((glueChannel) => {
4310
+ const userChannel = this.buildChannel(ChannelTypes.User, { displayMetadata: { glueChannel } });
4311
+ this.stateStore.addFdc3IdToGlueChannelName(userChannel.id, glueChannel.name);
4312
+ this.stateStore.addUserChannel(userChannel);
4313
+ if (current && glueChannel.name === current) {
4314
+ this.stateStore.currentChannel = userChannel;
4315
+ }
4316
+ });
4317
+ this.glueController.setOnChannelChanged(this.handleOnChannelChanged.bind(this));
4318
+ }
4319
+ async handleOnChannelChanged(channelId) {
4320
+ if (!channelId) {
4321
+ return;
4322
+ }
4323
+ const isFdc3ChannelName = fdc3ChannelNames.includes(channelId);
4324
+ const userChannelId = isFdc3ChannelName ? channelId : this.stateStore.getFdc3ChannelIdByGlueChannelName(channelId);
4325
+ this.stateStore.currentChannel = this.stateStore.userChannels[userChannelId];
4326
+ }
4327
+ isBroadcastPermitted(commandId, channelId) {
4328
+ if (channelId) {
4329
+ return true;
4330
+ }
4331
+ if (!this.stateStore.currentChannel) {
4332
+ this.logger?.info(`[${commandId}] - invocation of broadcast ignored - no channel to broadcast to`);
4333
+ console.warn("You need to join a user channel in order to broadcast");
4334
+ return false;
4335
+ }
4336
+ if (this.stateStore.currentChannel.type === ChannelTypes.App) {
4337
+ this.logger?.info(`[${commandId}] - invocation of broadcast ignored - cannot broadcast on app channel directly`);
4338
+ console.error("You can't broadcast to an app channel directly - use channel's broadcast method instead");
4339
+ return false;
4340
+ }
4341
+ return true;
4342
+ }
4343
+ async handleWindowContextOnOpening(commandId, handler, contextType) {
4344
+ const myWindow = this.glueController.getMyWindow();
4345
+ if (!myWindow) {
4346
+ this.logger?.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
4347
+ this.invokeContextHandlerWithStartupContext = false;
4348
+ return;
4349
+ }
4350
+ const windowContext = await myWindow.getContext();
4351
+ if (!windowContext) {
4352
+ this.logger?.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
4353
+ this.invokeContextHandlerWithStartupContext = false;
4354
+ return;
4355
+ }
4356
+ if (!isValidNonEmptyObject(windowContext) || !windowContext.fdc3) {
4357
+ this.logger?.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
4358
+ this.invokeContextHandlerWithStartupContext = false;
4359
+ return;
4360
+ }
4361
+ await this.glueEventsController.initializeCollaborateMethod();
4362
+ FDC3StartupContextDecoder.runWithException(windowContext);
4363
+ const { fdc3 } = windowContext;
4364
+ this.logger?.trace(`[${commandId}] - received FDC3 startup context from ${JSON.stringify(fdc3.openApp)} for contextType ${fdc3.context.contextType}`);
4365
+ const isSameContextType = contextType ? fdc3.context.contextType === contextType : true;
4366
+ if (!isSameContextType) {
4367
+ this.logger?.info(`[${commandId}] - addContextListener handler won't be invoked for contextType ${contextType} for startup context with type: ${fdc3.context.contextType}`);
4368
+ return;
4369
+ }
4370
+ this.logger?.info(`[${commandId}] - invoking addContextListener handler with startup context with type ${fdc3.context.contextType}`);
4371
+ try {
4372
+ handler(fdc3.context.payload, { source: fdc3.openApp });
4373
+ }
4374
+ catch (error) {
4375
+ const errorMsg = error.message ? JSON.stringify(error.message) : JSON.stringify(error);
4376
+ this.logger?.error(typeof error === "string" ? error : errorMsg);
4377
+ }
4378
+ this.invokeContextHandlerWithStartupContext = false;
4379
+ this.logger?.trace(`[${commandId}] - invoking response method to with target ${JSON.stringify(fdc3.openApp)}`);
4380
+ await this.invokeSystemMethod({ action: "startupContextOpened", correlationId: fdc3.collaborationId }, fdc3.openApp.instanceId);
4381
+ this.logger?.trace(`[${commandId}] - system method invocation success for 'startupContextOpened' heard`);
4382
+ }
4383
+ async getOrCreateAppChannel(commandId, channelId) {
4384
+ const exists = this.doesAppChannelExist(channelId);
4385
+ if (!exists) {
4386
+ this.logger?.info(`[${commandId}] - app channel with id ${channelId} does not exist. Creating one`);
4387
+ await this.glueController.updateContext(channelId, {});
4388
+ }
4389
+ this.logger?.info(`[${commandId}] - returning app channel with id ${channelId}`);
4390
+ const logger = this.glueController.initSubLogger(`app.channel.${channelId}`);
4391
+ return this.buildChannel(ChannelTypes.App, { id: channelId, logger });
4392
+ }
4393
+ doesAppChannelExist(name) {
4394
+ return !name.includes(PrivateChannelPrefix) && this.glueController.getAllContexts().some((ctxName) => ctxName === name);
4395
+ }
4396
+ isUserChannel(channelId) {
4397
+ if (!channelId) {
4398
+ return false;
4399
+ }
4400
+ return !!this.stateStore.userChannels[channelId];
4401
+ }
4402
+ async broadcastByChannelId(commandId, channelId, context) {
4403
+ const isUserChannel = this.isUserChannel(channelId);
4404
+ if (!isUserChannel) {
4405
+ this.logger?.info(`[${commandId}] - broadcasting on app channel with id ${channelId}`);
4406
+ return this.glueController.updateContextWithLatestFdc3Type(channelId, context);
4407
+ }
4408
+ const ioChannelName = this.stateStore.getGlueChannelNameByFdc3ChannelId(channelId);
4409
+ this.logger?.info(`[${commandId}] - broadcasting on fdc3 user channel with id ${channelId} (underlying glue channel: ${ioChannelName})`);
4410
+ return this.userChannelsSupportController.broadcast({ ioChannelName, context });
4411
+ }
4412
+ async addContextListenerWithoutChannelId({ commandId, contextType, handler }) {
4413
+ this.logger?.info(`[${commandId}] - Creating a channel subscription using glue.channels.subscribe`);
4414
+ const subHandler = parseContextHandler(handler, contextType);
4415
+ const unsubscribe = this.glueController.legacyChannelsSubscribe(subHandler, contextType);
4416
+ return { unsubscribe };
4417
+ }
4418
+ async addContextListenerByChannelId({ commandId, channelId, handler, contextType, invokedOnChannelModel }) {
4419
+ const subHandler = parseContextHandler(handler, contextType);
4420
+ const channelType = this.getChannelTypeById(channelId);
4421
+ if (channelType === ChannelTypes.User) {
4422
+ return this.userChannelsSupportController.addContextListener({ commandId, channelId, handler: subHandler, contextType, invokedOnChannelModel });
4423
+ }
4424
+ if (channelType === ChannelTypes.App) {
4425
+ this.logger?.info(`[${commandId}] - subscribing for fdc3 app channel with id ${channelId} (underlying glue context with same name)`);
4426
+ const unsubscribe = await this.glueController.contextsSubscribe(channelId, subHandler);
4427
+ return {
4428
+ unsubscribe: () => {
4429
+ this.logger?.info(`[${commandId}] - invoking unsubscribe for app channel with id ${channelId}`);
4430
+ unsubscribe();
4431
+ }
4432
+ };
4433
+ }
4434
+ this.logger?.error("Cannot add a context listener on an invalid channel");
4435
+ throw new Error(ChannelError.AccessDenied);
4436
+ }
4437
+ getChannelTypeById(channelId) {
4438
+ const isUser = this.isUserChannel(channelId);
4439
+ if (isUser) {
4440
+ return ChannelTypes.User;
4441
+ }
4442
+ const isApp = this.doesAppChannelExist(channelId);
4443
+ if (isApp) {
4444
+ return ChannelTypes.App;
4445
+ }
4446
+ this.logger?.error(`Channel with id: ${channelId} does not exist`);
4447
+ throw new Error(ChannelError.NoChannelFound);
4448
+ }
4449
+ }
4450
+
4451
+ class LegacyDataWrappingChannelsController {
4452
+ parser;
4453
+ stateStore;
4454
+ glueController;
4455
+ _logger;
4456
+ constructor(parser, stateStore, glueController) {
4457
+ this.parser = parser;
4458
+ this.stateStore = stateStore;
4459
+ this.glueController = glueController;
4460
+ }
4461
+ async getContext({ commandId, channelId, contextType }) {
4462
+ this.logger?.info(`[${commandId}] - retrieving latest context of type ${contextType} broadcasted on channel with id ${channelId}`);
4463
+ if (!contextType) {
4464
+ const glueChannelName = this.stateStore.getGlueChannelNameByFdc3ChannelId(channelId);
4465
+ const glueChannelWithPrefix = this.parser.mapChannelNameToContextName(glueChannelName);
4466
+ this.logger?.info(`[${commandId}] - getting context for user channel with id ${channelId} (underlying glue channel ${glueChannelName})`);
4467
+ const context = await this.glueController.getContext(glueChannelWithPrefix);
4468
+ return context.latest_fdc3_type ? this.parser.parseContextsDataToInitialFDC3Data(context) : null;
4469
+ }
4470
+ const parsedType = this.parser.mapFDC3TypeToChannelsDelimiter(contextType);
4471
+ const { data } = await this.glueController.getChannel(this.stateStore.getGlueChannelNameByFdc3ChannelId(channelId));
4472
+ return data?.[`fdc3_${parsedType}`]
4473
+ ? this.parser.parseContextsDataToInitialFDC3Data({ data, latest_fdc3_type: parsedType })
4474
+ : null;
4475
+ }
4476
+ async broadcast({ ioChannelName, context }) {
4477
+ const { path, value } = this.parser.parseFDC3ContextToGlueContexts(context);
4478
+ return this.glueController.channelsUpdate({ [path]: value }, ioChannelName);
4479
+ }
4480
+ async addContextListener({ commandId, channelId, handler, invokedOnChannelModel, contextType }) {
4481
+ if (!invokedOnChannelModel) {
4482
+ this.logger?.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
4483
+ const unsubscribe = this.glueController.legacyChannelsSubscribe(handler, contextType);
4484
+ return { unsubscribe };
4485
+ }
4486
+ const contextToSubscribeTo = this.parser.mapChannelNameToContextName(this.stateStore.getGlueChannelNameByFdc3ChannelId(channelId));
4487
+ this.logger?.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
4488
+ const unsubscribe = await this.glueController.contextsSubscribe(contextToSubscribeTo, handler);
4489
+ return { unsubscribe };
4490
+ }
4491
+ get logger() {
4492
+ if (!this._logger) {
4493
+ this._logger = this.glueController.initSubLogger("fdc3.legacy.channels.controller");
4494
+ }
4495
+ return this._logger;
4496
+ }
4497
+ }
4498
+
4499
+ class NewDataWrappingChannelsController {
4500
+ parser;
4501
+ stateStore;
4502
+ glueController;
4503
+ _logger;
4504
+ constructor(parser, stateStore, glueController) {
4505
+ this.parser = parser;
4506
+ this.stateStore = stateStore;
4507
+ this.glueController = glueController;
4508
+ }
4509
+ async getContext({ commandId, channelId, contextType }) {
4510
+ this.logger?.info(`[${commandId}] - retrieving latest context of type ${contextType} broadcasted on channel with id ${channelId}`);
4511
+ const ioChannelName = this.stateStore.getGlueChannelNameByFdc3ChannelId(channelId);
4512
+ const ioChannel = await this.glueController.getChannel(ioChannelName);
4513
+ if (!contextType) {
4514
+ return ioChannel.data.fdc3 || null;
4515
+ }
4516
+ if (contextType && ioChannel.data.fdc3?.type === contextType) {
4517
+ return ioChannel.data.fdc3;
4518
+ }
4519
+ const ioChannelContextName = this.parser.mapChannelNameToContextName(ioChannelName);
4520
+ const { data } = await this.glueController.getContext(ioChannelContextName);
4521
+ const parsedType = this.parser.mapFDC3TypeToChannelsDelimiter(contextType);
4522
+ return data?.[`fdc3_${parsedType}`]
4523
+ ? this.parser.parseContextsDataToInitialFDC3Data({ data, latest_fdc3_type: parsedType })
4524
+ : null;
4525
+ }
4526
+ async broadcast({ ioChannelName, context }) {
4527
+ return this.glueController.channelsUpdate(context, { name: ioChannelName, fdc3: true });
4528
+ }
4529
+ async addContextListener({ commandId, channelId, invokedOnChannelModel, handler, contextType }) {
4530
+ if (!invokedOnChannelModel) {
4531
+ this.logger?.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
4532
+ const unsubscribe = this.glueController.channelsSubscribe(handler, contextType);
4533
+ return { unsubscribe };
4534
+ }
4535
+ const contextToSubscribeTo = this.parser.mapChannelNameToContextName(this.stateStore.getGlueChannelNameByFdc3ChannelId(channelId));
4536
+ this.logger?.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
4537
+ const unsubscribe = await this.glueController.contextsSubscribe(contextToSubscribeTo, handler);
4538
+ return { unsubscribe };
4539
+ }
4540
+ get logger() {
4541
+ if (!this._logger) {
4542
+ this._logger = this.glueController.initSubLogger("fdc3.ioSupport.channels.controller");
4543
+ }
4544
+ return this._logger;
4545
+ }
4546
+ }
4547
+
4548
+ class IoC {
4549
+ _eventDispatcher;
4550
+ _eventReceiver;
4551
+ _desktopAgent;
4552
+ _glueController;
4553
+ _intentsController;
4554
+ _applicationController;
4555
+ _channelsBaseController;
4556
+ _legacyDataWrappingChannelsController;
4557
+ _newDataWrappingChannelsController;
4558
+ _channelsParser;
4559
+ _channelsStateStore;
4560
+ _channelsFactory;
4561
+ _fdc3;
4562
+ _eventsController;
4563
+ _applicationsStateStore;
4564
+ get ioc() {
4565
+ return this;
4566
+ }
4567
+ get eventReceiver() {
4568
+ if (!this._eventReceiver) {
4569
+ this._eventReceiver = new EventReceiver(this.glueController, this.eventDispatcher);
4570
+ }
4571
+ return this._eventReceiver;
4544
4572
  }
4545
4573
  get glueController() {
4546
4574
  if (!this._glueController) {
@@ -4567,17 +4595,17 @@ class IoC {
4567
4595
  return this._channelsFactory;
4568
4596
  }
4569
4597
  createUserChannel(glueChannel) {
4570
- return new UserChannel(this.channelsController, glueChannel).toApi();
4598
+ return new UserChannel(this.channelsBaseController, glueChannel).toApi();
4571
4599
  }
4572
4600
  createAppChannel(id) {
4573
- return new AppChannel(this.channelsController, id).toApi();
4601
+ return new AppChannel(this.channelsBaseController, id).toApi();
4574
4602
  }
4575
4603
  createPrivateChannel(logger, channelId, isCreator) {
4576
- return new PrivateChannel(this.channelsController, logger, channelId, isCreator);
4604
+ return new PrivateChannel(this.channelsBaseController, logger, channelId, isCreator);
4577
4605
  }
4578
4606
  get desktopAgent() {
4579
4607
  if (!this._desktopAgent) {
4580
- this._desktopAgent = new DesktopAgent(this.intentsController, this.applicationController, this.channelsController);
4608
+ this._desktopAgent = new DesktopAgent(this.intentsController, this.applicationController, this.channelsBaseController);
4581
4609
  }
4582
4610
  return this._desktopAgent;
4583
4611
  }
@@ -4589,7 +4617,7 @@ class IoC {
4589
4617
  }
4590
4618
  get intentsController() {
4591
4619
  if (!this._intentsController) {
4592
- this._intentsController = new IntentsController(this.glueController, this.channelsController, this.channelsFactory, this.eventsController);
4620
+ this._intentsController = new IntentsController(this.glueController, this.channelsBaseController, this.channelsFactory, this.eventsController);
4593
4621
  }
4594
4622
  return this._intentsController;
4595
4623
  }
@@ -4599,11 +4627,23 @@ class IoC {
4599
4627
  }
4600
4628
  return this._applicationController;
4601
4629
  }
4602
- get channelsController() {
4603
- if (!this._channelsController) {
4604
- this._channelsController = new ChannelsController(this.glueController, this.channelsStateStore, this.channelsParser, this.channelsFactory, this.eventsController);
4630
+ get channelsBaseController() {
4631
+ if (!this._channelsBaseController) {
4632
+ this._channelsBaseController = new ChannelsBaseController(this.glueController, this.channelsStateStore, this.channelsParser, this.channelsFactory, this.eventsController, this.legacyDataWrappingChannelsController, this.ioFdc3SupportChannelsController);
4633
+ }
4634
+ return this._channelsBaseController;
4635
+ }
4636
+ get legacyDataWrappingChannelsController() {
4637
+ if (!this._legacyDataWrappingChannelsController) {
4638
+ this._legacyDataWrappingChannelsController = new LegacyDataWrappingChannelsController(this.channelsParser, this.channelsStateStore, this.glueController);
4639
+ }
4640
+ return this._legacyDataWrappingChannelsController;
4641
+ }
4642
+ get ioFdc3SupportChannelsController() {
4643
+ if (!this._newDataWrappingChannelsController) {
4644
+ this._newDataWrappingChannelsController = new NewDataWrappingChannelsController(this.channelsParser, this.channelsStateStore, this.glueController);
4605
4645
  }
4606
- return this._channelsController;
4646
+ return this._newDataWrappingChannelsController;
4607
4647
  }
4608
4648
  get channelsStateStore() {
4609
4649
  if (!this._channelsStateStore) {