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