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