@interopio/fdc3 2.1.1 → 2.1.3

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.
@@ -124,17 +124,95 @@
124
124
  const defaultChannelsProps = ["id", "type", "broadcast", "addContextListener", "getCurrentContext"];
125
125
  const defaultContextProps = ["type"];
126
126
  const defaultGlue42APIs = ["contexts", "channels", "interop", "intents", "appManager", "windows"];
127
- const responseInteropMethodPrefix = "T42.FDC3.Open.Listener.Response";
128
127
  const glueChannelNamePrefix = "___channel___";
129
128
  const fdc3NothingContextType = "fdc3.nothing";
130
129
  const Glue42EnterpriseNoAppWindow = "no-app-window";
131
130
  const RaiseTimeoutMs = 75 * 1000;
132
- const IntentsMethodPrefix = "Tick42.FDC3.Intents.";
131
+ const IntentsMethodPrefix = "Tick42.FDC3.Intents.";
132
+ const Fdc3SupportedIntentTypes = {
133
+ "CreateInteraction": [
134
+ "fdc3.contactList",
135
+ "fdc3.interaction"
136
+ ],
137
+ "StartCall": [
138
+ "fdc3.contact",
139
+ "fdc3.contactList"
140
+ ],
141
+ "StartChat": [
142
+ "fdc3.contact",
143
+ "fdc3.contactList",
144
+ "fdc3.chat.initSettings"
145
+ ],
146
+ "StartEmail": [
147
+ "fdc3.email"
148
+ ],
149
+ "SendChatMessage": [
150
+ "fdc3.chat.message"
151
+ ],
152
+ "ViewAnalysis": [
153
+ "fdc3.instrument",
154
+ "fdc3.organization",
155
+ "fdc3.portfolio"
156
+ ],
157
+ "ViewChat": [
158
+ "fdc3.chat.room",
159
+ "fdc3.contact",
160
+ "fdc3.contactList"
161
+ ],
162
+ "ViewChart": [
163
+ "fdc3.chart",
164
+ "fdc3.instrument",
165
+ "fdc3.instrumentList",
166
+ "fdc3.portfolio",
167
+ "fdc3.position"
168
+ ],
169
+ "ViewHoldings": [
170
+ "fdc3.instrument",
171
+ "fdc3.instrumentList",
172
+ "fdc3.organization"
173
+ ],
174
+ "ViewInstrument": [
175
+ "fdc3.instrument"
176
+ ],
177
+ "ViewInteractions": [
178
+ "fdc3.contact",
179
+ "fdc3.instrument",
180
+ "fdc3.organization"
181
+ ],
182
+ "ViewMessages": [
183
+ "fdc3.chat.searchCriteria"
184
+ ],
185
+ "ViewNews": [
186
+ "fdc3.country",
187
+ "fdc3.instrument",
188
+ "fdc3.instrumentList",
189
+ "fdc3.organization",
190
+ "fdc3.portfolio"
191
+ ],
192
+ "ViewOrders": [
193
+ "fdc3.contact",
194
+ "fdc3.instrument",
195
+ "fdc3.organization"
196
+ ],
197
+ "ViewProfile": [
198
+ "fdc3.contact",
199
+ "fdc3.organization"
200
+ ],
201
+ "ViewQuote": [
202
+ "fdc3.instrument"
203
+ ],
204
+ "ViewResearch": [
205
+ "fdc3.contact",
206
+ "fdc3.instrument",
207
+ "fdc3.organization"
208
+ ]
209
+ };
133
210
 
134
- const Glue42FDC3SystemMethod = "T42.FDC3.Client.Control";
211
+ const ioConnectFDC3SystemMethod = "FDC3.Collaborate";
135
212
  const PrivateChannelPrefix = "___privateFDC3Channel___";
136
213
  var PrivateChannelEventMethods;
137
214
  (function (PrivateChannelEventMethods) {
215
+ PrivateChannelEventMethods["ListenerAdded"] = "listenerAdded";
138
216
  PrivateChannelEventMethods["OnAddContextListener"] = "onAddContextListener";
139
217
  PrivateChannelEventMethods["OnUnsubscribe"] = "onUnsubscribe";
140
218
  PrivateChannelEventMethods["OnDisconnect"] = "onDisconnect";
@@ -887,7 +965,7 @@
887
965
  /** See `Decoder.number` */
888
966
  var number = Decoder.number;
889
967
  /** See `Decoder.boolean` */
890
- var boolean = Decoder.boolean;
968
+ Decoder.boolean;
891
969
  /** See `Decoder.anyJson` */
892
970
  var anyJson = Decoder.anyJson;
893
971
  /** See `Decoder.unknownJson` */
@@ -959,31 +1037,35 @@
959
1037
  const optionalTargetApp = optional(appIdentifierDecoder);
960
1038
  const optionalAppIdentifier = optional(targetAppDecoder);
961
1039
  const optionalNonEmptyStringDecoder = optional(nonEmptyStringDecoder);
962
- const SystemMethodActionDecider = oneOf(constant(PrivateChannelEventMethods.OnAddContextListener), constant(PrivateChannelEventMethods.OnUnsubscribe), constant(PrivateChannelEventMethods.OnDisconnect));
963
- const SystemMethodEventPayloadDecoder = object({
964
- channelId: nonEmptyStringDecoder,
965
- clientId: nonEmptyStringDecoder,
966
- contextType: optional(string()),
967
- replayContextTypes: optional(array(string()))
1040
+ const SystemMethodActionDecoder = oneOf(constant("joinPrivateChannel"), constant("publishOnPrivateChannel"), constant("addedContextListenerOnPrivateChannel"), constant("removedContextListenerOnPrivateChannel"), constant("disconnectedFromPrivateChannel"), constant("startupContextOpened"));
1041
+ const CollaborationObjectDecoder = object({
1042
+ channelId: optional(nonEmptyStringDecoder),
1043
+ contextType: optional(nonEmptyStringDecoder),
1044
+ payload: optional(contextDecoder)
968
1045
  });
969
1046
  const SystemMethodInvocationArgumentDecoder = object({
970
- action: SystemMethodActionDecider,
971
- payload: SystemMethodEventPayloadDecoder
972
- });
973
- const ContextListenerResponseDecoder = object({
974
- listenerInvoked: optional(boolean())
1047
+ action: SystemMethodActionDecoder,
1048
+ correlationId: nonEmptyStringDecoder,
1049
+ collaborationObject: optional(CollaborationObjectDecoder)
975
1050
  });
976
- object({
977
- meta: object({
978
- responseMethodName: nonEmptyStringDecoder
979
- }),
980
- context: contextDecoder
1051
+ const FDC3StartupContextDecoder = object({
1052
+ fdc3: object({
1053
+ collaborationId: nonEmptyStringDecoder,
1054
+ openApp: object({
1055
+ appId: nonEmptyStringDecoder,
1056
+ instanceId: nonEmptyStringDecoder
1057
+ }),
1058
+ context: object({
1059
+ contextType: optional(string()),
1060
+ payload: contextDecoder
1061
+ })
1062
+ })
981
1063
  });
982
1064
 
983
1065
  class GlueController {
984
1066
  constructor(channelsParser) {
985
1067
  this.channelsParser = channelsParser;
986
- this.defaultGluePromiseTimeout = 120000;
1068
+ this.defaultGluePromiseTimeout = 120 * 1000;
987
1069
  }
988
1070
  get gluePromise() {
989
1071
  return this.glueInitPromise.then(this.initializeLogger.bind(this));
@@ -1039,6 +1121,15 @@
1039
1121
  return this.glue.intents.raise(request);
1040
1122
  });
1041
1123
  }
1124
+ getMyWindowContext() {
1125
+ return __awaiter(this, void 0, void 0, function* () {
1126
+ const myWin = this.getMyWindow();
1127
+ if (!myWin) {
1128
+ return;
1129
+ }
1130
+ return myWin.getContext();
1131
+ });
1132
+ }
1042
1133
  addIntentListener(intent, handler) {
1043
1134
  const registerMethodExists = this.glue.intents.register;
1044
1135
  return registerMethodExists
@@ -1106,8 +1197,8 @@
1106
1197
  const win = this.glue.windows.my();
1107
1198
  return isValidNonEmptyObject(win) ? win : undefined;
1108
1199
  }
1109
- getMyInteropInstanceId() {
1110
- return this.glue.interop.instance.instance;
1200
+ getMyInteropInstance() {
1201
+ return this.glue.interop.instance;
1111
1202
  }
1112
1203
  getGlueVersion() {
1113
1204
  var _a;
@@ -1116,21 +1207,14 @@
1116
1207
  registerOnInstanceStopped(cb) {
1117
1208
  return this.glue.appManager.onInstanceStopped(cb);
1118
1209
  }
1119
- invokeMethod(methodName, instance, argumentObj) {
1120
- return __awaiter(this, void 0, void 0, function* () {
1121
- const args = ContextListenerResponseDecoder.runWithException(argumentObj);
1122
- return this.glue.interop.invoke(methodName, args, { instance });
1123
- });
1124
- }
1125
1210
  unregisterMethod(methodName) {
1126
1211
  return __awaiter(this, void 0, void 0, function* () {
1127
1212
  return this.glue.interop.unregister(methodName);
1128
1213
  });
1129
1214
  }
1130
- invokeSystemMethod(argumentObj) {
1131
- const args = SystemMethodInvocationArgumentDecoder.runWithException(argumentObj);
1132
- const target = args.payload.clientId;
1133
- return this.glue.interop.invoke(Glue42FDC3SystemMethod, args, { instance: target });
1215
+ invokeSystemMethod(argumentObj, target) {
1216
+ SystemMethodInvocationArgumentDecoder.runWithException(argumentObj);
1217
+ return this.glue.interop.invoke(ioConnectFDC3SystemMethod, argumentObj, { instance: target });
1134
1218
  }
1135
1219
  registerMethod(name, handler) {
1136
1220
  return this.glue.interop.register(name, handler);
@@ -1140,21 +1224,16 @@
1140
1224
  }
1141
1225
  channelsSubscribe(callback, contextType) {
1142
1226
  const didReplay = { replayed: false };
1143
- return this.glue.channels.subscribe((_, context, updaterId) => __awaiter(this, void 0, void 0, function* () {
1144
- if (this.isUpdateFromMe(updaterId) || !context) {
1227
+ return this.glue.channels.subscribe((_, contextData, updaterId) => {
1228
+ if (this.isUpdateFromMe(updaterId) || !contextData || !contextData.latest_fdc3_type) {
1145
1229
  return;
1146
1230
  }
1147
- const contextData = yield this.glue.contexts.get(`${glueChannelNamePrefix}${context.name}`);
1148
- if (!contextData.latest_fdc3_type) {
1149
- return;
1150
- }
1151
- if (!didReplay.replayed) {
1152
- this.invokePreviouslyBroadcastedData({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
1153
- didReplay.replayed = true;
1154
- return;
1231
+ if (didReplay.replayed) {
1232
+ return this.parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
1155
1233
  }
1156
- this.parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
1157
- }));
1234
+ this.invokePreviouslyBroadcastedData({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
1235
+ didReplay.replayed = true;
1236
+ });
1158
1237
  }
1159
1238
  contextsSubscribe(contextName, callback) {
1160
1239
  const didReplay = { replayed: false };
@@ -1175,10 +1254,11 @@
1175
1254
  return this.logger.subLogger(name);
1176
1255
  }
1177
1256
  invokePreviouslyBroadcastedData({ callback, contextData, metadata, contextType }) {
1178
- if (!contextData.latest_fdc3_type) {
1179
- return;
1257
+ const invokeForType = contextType || this.channelsParser.mapChannelsDelimiterToFDC3Type(contextData.latest_fdc3_type);
1258
+ const dataForContextType = this.getLatestBroadcastedDataByContextType(contextData, invokeForType);
1259
+ if (dataForContextType) {
1260
+ callback(dataForContextType, metadata);
1180
1261
  }
1181
- this.parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata, contextType });
1182
1262
  }
1183
1263
  isUpdateFromMe(updaterId) {
1184
1264
  return this.glue.interop.instance.peerId === updaterId;
@@ -1200,19 +1280,22 @@
1200
1280
  }
1201
1281
  parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata, contextType }) {
1202
1282
  if (!contextType) {
1203
- const parsedData = this.channelsParser.parseContextsDataToInitialFDC3Data(contextData);
1283
+ const parsedData = this.channelsParser.parseContextsDataToInitialFDC3Data({ data: contextData.data, latest_fdc3_type: contextData.latest_fdc3_type });
1204
1284
  callback(parsedData, metadata);
1205
1285
  return;
1206
1286
  }
1207
- const dataForContextType = this.getLatestBroadcastedDataByContextType(contextData, contextType);
1208
- if (!dataForContextType) {
1287
+ const latestPublishedType = this.channelsParser.mapChannelsDelimiterToFDC3Type(contextData.latest_fdc3_type);
1288
+ if (latestPublishedType !== contextType) {
1209
1289
  return;
1210
1290
  }
1211
- callback(dataForContextType, metadata);
1291
+ const dataForContextType = this.getLatestBroadcastedDataByContextType(contextData, contextType);
1292
+ if (dataForContextType) {
1293
+ callback(dataForContextType, metadata);
1294
+ }
1212
1295
  }
1213
1296
  getLatestBroadcastedDataByContextType(contextData, contextType) {
1214
1297
  let foundData;
1215
- Object.entries(contextData.data).find(([key, value]) => {
1298
+ Object.entries(contextData.data).forEach(([key, value]) => {
1216
1299
  if (!this.channelsParser.isFdc3DataKey(key)) {
1217
1300
  return;
1218
1301
  }
@@ -1274,6 +1357,7 @@
1274
1357
  }
1275
1358
  toApi() {
1276
1359
  const api = {
1360
+ getStartupContext: this.getStartupContext.bind(this),
1277
1361
  addContextListener: this.addContextListener.bind(this),
1278
1362
  addIntentListener: this.addIntentListener.bind(this),
1279
1363
  broadcast: this.broadcast.bind(this),
@@ -1386,6 +1470,11 @@
1386
1470
  return this.intentsController.addIntentListener({ commandId: generateCommandId(), intent, handler });
1387
1471
  });
1388
1472
  }
1473
+ getStartupContext() {
1474
+ return __awaiter(this, void 0, void 0, function* () {
1475
+ return this.channelsController.getStartupContext();
1476
+ });
1477
+ }
1389
1478
  getOrCreateChannel(channelId) {
1390
1479
  return __awaiter(this, void 0, void 0, function* () {
1391
1480
  nonEmptyStringDecoder.runWithException(channelId);
@@ -1508,76 +1597,60 @@
1508
1597
  * SPDX-License-Identifier: Apache-2.0
1509
1598
  * Copyright FINOS FDC3 contributors - see NOTICE file
1510
1599
  */
1511
-
1512
1600
  /** Constants representing the errors that can be encountered when calling the `open` method on the DesktopAgent object (`fdc3`). */
1513
1601
  var OpenError;
1514
-
1515
1602
  (function (OpenError) {
1516
1603
  /** Returned if the specified application is not found.*/
1517
1604
  OpenError["AppNotFound"] = "AppNotFound";
1518
1605
  /** Returned if the specified application fails to launch correctly.*/
1519
-
1520
1606
  OpenError["ErrorOnLaunch"] = "ErrorOnLaunch";
1521
1607
  /** Returned if the specified application launches but fails to add a context listener in order to receive the context passed to the `fdc3.open` call.*/
1522
-
1523
1608
  OpenError["AppTimeout"] = "AppTimeout";
1524
1609
  /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
1525
-
1526
1610
  OpenError["ResolverUnavailable"] = "ResolverUnavailable";
1611
+ /** Returned if a call to the `open` function is made with an invalid context argument. Contexts should be Objects with at least a `type` field that has a `string` value.*/
1612
+ OpenError["MalformedContext"] = "MalformedContext";
1527
1613
  })(OpenError || (OpenError = {}));
1528
1614
  /** Constants representing the errors that can be encountered when calling the `findIntent`, `findIntentsByContext`, `raiseIntent` or `raiseIntentForContext` methods on the DesktopAgent (`fdc3`). */
1529
-
1530
-
1531
1615
  var ResolveError;
1532
-
1533
1616
  (function (ResolveError) {
1534
1617
  /** SHOULD be returned if no apps are available that can resolve the intent and context combination.*/
1535
1618
  ResolveError["NoAppsFound"] = "NoAppsFound";
1536
1619
  /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
1537
-
1538
1620
  ResolveError["ResolverUnavailable"] = "ResolverUnavailable";
1539
1621
  /** Returned if the user cancelled the resolution request, for example by closing or cancelling a resolver UI.*/
1540
-
1541
1622
  ResolveError["UserCancelled"] = "UserCancelledResolution";
1542
1623
  /** SHOULD be returned if a timeout cancels an intent resolution that required user interaction. Please use `ResolverUnavailable` instead for situations where a resolver UI or similar fails.*/
1543
-
1544
1624
  ResolveError["ResolverTimeout"] = "ResolverTimeout";
1545
1625
  /** Returned if a specified target application is not available or a new instance of it cannot be opened. */
1546
-
1547
1626
  ResolveError["TargetAppUnavailable"] = "TargetAppUnavailable";
1548
1627
  /** Returned if a specified target application instance is not available, for example because it has been closed. */
1549
-
1550
1628
  ResolveError["TargetInstanceUnavailable"] = "TargetInstanceUnavailable";
1551
1629
  /** Returned if the intent and context could not be delivered to the selected application or instance, for example because it has not added an intent handler within a timeout.*/
1552
-
1553
1630
  ResolveError["IntentDeliveryFailed"] = "IntentDeliveryFailed";
1631
+ /** Returned if a call to one of the `raiseIntent` functions is made with an invalid context argument. Contexts should be Objects with at least a `type` field that has a `string` value.*/
1632
+ ResolveError["MalformedContext"] = "MalformedContext";
1554
1633
  })(ResolveError || (ResolveError = {}));
1555
-
1556
1634
  var ResultError;
1557
-
1558
1635
  (function (ResultError) {
1559
- /** Returned if the intent handler exited without returning a Promise or that Promise was not resolved with a Context or Channel object. */
1636
+ /** Returned if the intent handler exited without returning a valid result (a promise resolving to a Context, Channel object or void). */
1560
1637
  ResultError["NoResultReturned"] = "NoResultReturned";
1561
1638
  /** Returned if the Intent handler function processing the raised intent throws an error or rejects the Promise it returned. */
1562
-
1563
1639
  ResultError["IntentHandlerRejected"] = "IntentHandlerRejected";
1564
1640
  })(ResultError || (ResultError = {}));
1565
-
1566
1641
  var ChannelError;
1567
-
1568
1642
  (function (ChannelError) {
1569
1643
  /** Returned if the specified channel is not found when attempting to join a channel via the `joinUserChannel` function of the DesktopAgent (`fdc3`).*/
1570
1644
  ChannelError["NoChannelFound"] = "NoChannelFound";
1571
1645
  /** SHOULD be returned when a request to join a user channel or to a retrieve a Channel object via the `joinUserChannel` or `getOrCreateChannel` methods of the DesktopAgent (`fdc3`) object is denied. */
1572
-
1573
1646
  ChannelError["AccessDenied"] = "AccessDenied";
1574
1647
  /** SHOULD be returned when a channel cannot be created or retrieved via the `getOrCreateChannel` method of the DesktopAgent (`fdc3`).*/
1575
-
1576
1648
  ChannelError["CreationFailed"] = "CreationFailed";
1649
+ /** Returned if a call to the `broadcast` functions is made with an invalid context argument. Contexts should be Objects with at least a `type` field that has a `string` value.*/
1650
+ ChannelError["MalformedContext"] = "MalformedContext";
1577
1651
  })(ChannelError || (ChannelError = {}));
1578
1652
 
1579
1653
  var ContextTypes;
1580
-
1581
1654
  (function (ContextTypes) {
1582
1655
  ContextTypes["Chart"] = "fdc3.chart";
1583
1656
  ContextTypes["ChatInitSettings"] = "fdc3.chat.initSettings";
@@ -1598,13 +1671,13 @@
1598
1671
 
1599
1672
  // To parse this data:
1600
1673
  //
1601
- // import { Convert, Context, Chart, ChatInitSettings, Contact, ContactList, Country, Currency, Email, Instrument, InstrumentList, Nothing, Organization, Portfolio, Position, TimeRange, Valuation } from "./file";
1674
+ // import { Convert, Chart, ChatInitSettings, Contact, ContactList, Context, Country, Currency, Email, Instrument, InstrumentList, Nothing, Organization, Portfolio, Position, TimeRange, Valuation } from "./file";
1602
1675
  //
1603
- // const context = Convert.toContext(json);
1604
1676
  // const chart = Convert.toChart(json);
1605
1677
  // const chatInitSettings = Convert.toChatInitSettings(json);
1606
1678
  // const contact = Convert.toContact(json);
1607
1679
  // const contactList = Convert.toContactList(json);
1680
+ // const context = Convert.toContext(json);
1608
1681
  // const country = Convert.toCountry(json);
1609
1682
  // const currency = Convert.toCurrency(json);
1610
1683
  // const email = Convert.toEmail(json);
@@ -1620,7 +1693,6 @@
1620
1693
  // These functions will throw an error if the JSON doesn't
1621
1694
  // match the expected interface, even if the JSON is valid.
1622
1695
  var Style;
1623
-
1624
1696
  (function (Style) {
1625
1697
  Style["Bar"] = "bar";
1626
1698
  Style["Candle"] = "candle";
@@ -1632,10 +1704,9 @@
1632
1704
  Style["Pie"] = "pie";
1633
1705
  Style["Scatter"] = "scatter";
1634
1706
  Style["StackedBar"] = "stacked-bar";
1635
- })(Style || (Style = {})); // Converts JSON strings to/from your types
1707
+ })(Style || (Style = {}));
1636
1708
 
1637
1709
  var Intents;
1638
-
1639
1710
  (function (Intents) {
1640
1711
  Intents["StartCall"] = "StartCall";
1641
1712
  Intents["StartChat"] = "StartChat";
@@ -1711,15 +1782,11 @@
1711
1782
  const isContext = (data) => {
1712
1783
  return defaultContextProps.every(prop => Object.keys(data).includes(prop));
1713
1784
  };
1714
- const isChannelMetadata = (data) => {
1715
- return typeof data === "object" && data.isChannel;
1716
- };
1717
1785
  const extractChannelMetadata = (channel) => {
1718
1786
  return {
1719
1787
  id: channel.id,
1720
1788
  type: channel.type,
1721
- displayMetadata: channel.displayMetadata,
1722
- isChannel: true
1789
+ displayMetadata: channel.displayMetadata
1723
1790
  };
1724
1791
  };
1725
1792
  const parseContextHandler = (handler, contextType) => {
@@ -1736,10 +1803,11 @@
1736
1803
  };
1737
1804
 
1738
1805
  class IntentsController {
1739
- constructor(glueController, channelsController, channelsFactory) {
1806
+ constructor(glueController, channelsController, channelsFactory, glueEventsController) {
1740
1807
  this.glueController = glueController;
1741
1808
  this.channelsController = channelsController;
1742
1809
  this.channelsFactory = channelsFactory;
1810
+ this.glueEventsController = glueEventsController;
1743
1811
  }
1744
1812
  get logger() {
1745
1813
  if (!this._logger) {
@@ -1831,11 +1899,33 @@
1831
1899
  });
1832
1900
  }
1833
1901
  addIntentListener({ commandId, intent, handler }) {
1902
+ var _a, _b;
1834
1903
  return __awaiter(this, void 0, void 0, function* () {
1835
1904
  yield this.glueController.gluePromise;
1836
1905
  this.logger.info(`[${commandId}] - addIntentListener() invoked for intent ${intent}`);
1837
1906
  const wrappedHandler = this.getWrappedIntentHandler(handler);
1838
- return this.glueController.addIntentListener(intent, wrappedHandler);
1907
+ const myInstance = this.glueController.getMyInteropInstance();
1908
+ const myApplication = this.glueController.getApplication(myInstance.applicationName);
1909
+ let appConfigIntentDef;
1910
+ const globalBrowserNamespace = window.glue42core || window.iobrowser;
1911
+ const globalDesktopNamespace = window.glue42gd || window.iodesktop;
1912
+ if (globalBrowserNamespace) {
1913
+ appConfigIntentDef = (_a = myApplication === null || myApplication === void 0 ? void 0 : myApplication.userProperties.intents) === null || _a === void 0 ? void 0 : _a.find((appIntent) => appIntent.name === intent);
1914
+ }
1915
+ if (globalDesktopNamespace) {
1916
+ const appConfig = yield myApplication.getConfiguration();
1917
+ appConfigIntentDef = (_b = appConfig === null || appConfig === void 0 ? void 0 : appConfig.intents) === null || _b === void 0 ? void 0 : _b.find((appIntent) => appIntent.name === intent);
1918
+ }
1919
+ const intentRequest = {
1920
+ intent,
1921
+ displayName: appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.displayName,
1922
+ description: appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.description,
1923
+ contextTypes: (appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.contexts) || Fdc3SupportedIntentTypes[intent],
1924
+ resultType: appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.resultType
1925
+ };
1926
+ Object.keys(intentRequest)
1927
+ .forEach((key) => intentRequest[key] === undefined && delete intentRequest[key]);
1928
+ return this.glueController.addIntentListener(intentRequest, wrappedHandler);
1839
1929
  });
1840
1930
  }
1841
1931
  filterGlueIntentHandlers({ commandId, intent, context, target }) {
@@ -1855,7 +1945,7 @@
1855
1945
  this.logger.info(`[${commandId}] - Checking if application with name ${appName} exists`);
1856
1946
  const app = this.glueController.getApplication(appName);
1857
1947
  const serverInstances = this.serverInstanceAsIntentHandler(intent.name);
1858
- if (!app && (typeof target === "string" || !serverInstances.length)) {
1948
+ if (!app && (typeof target === "string" || !target.instanceId || !serverInstances.length)) {
1859
1949
  throw { message: ResolveError.TargetAppUnavailable, reason: `There's no app with appId ${appName}` };
1860
1950
  }
1861
1951
  this.logger.info(`[${commandId}] - target app ${appName} found. Filtering handlers by applicationName: ${appName}`);
@@ -1901,23 +1991,33 @@
1901
1991
  if (!isValidNonEmptyObject(result)) {
1902
1992
  return;
1903
1993
  }
1904
- const isResultChannelMetadata = isChannelMetadata(result);
1905
- if (!isResultChannelMetadata) {
1994
+ if (!result.fdc3intentChannel && !result.fdc3intentContext) {
1906
1995
  return result;
1907
1996
  }
1908
- const { clientId, creatorId } = yield this.glueController.getContext(result.id);
1909
- this.logger.info(`[${commandId}] - result is a private channel with creatorId ${creatorId} and clientId ${clientId}`);
1910
- const myInteropInstanceId = this.glueController.getMyInteropInstanceId();
1911
- if ((creatorId && creatorId !== myInteropInstanceId) && (clientId && clientId !== myInteropInstanceId)) {
1912
- throw { message: ResultError.NoResultReturned, reason: "There are already two parties on this private channel" };
1913
- }
1914
- const channel = this.channelsFactory.buildModel(result);
1915
- if (myInteropInstanceId && myInteropInstanceId !== creatorId) {
1916
- this.logger.info(`[${commandId}] - the current user is the second party of the private channel. Adding my id ${myInteropInstanceId} as a clientId`);
1917
- yield this.channelsController.addClientToPrivateChannel(commandId, channel.id, myInteropInstanceId);
1918
- }
1997
+ if (result.fdc3intentContext) {
1998
+ return result.fdc3intentContext.payload;
1999
+ }
2000
+ const { fdc3intentChannel } = result;
2001
+ if (fdc3intentChannel.type === "user") {
2002
+ const glueChannel = (yield this.glueController.listAllChannels()).find(ch => ch.name === fdc3intentChannel.displayMetadata.name);
2003
+ return this.channelsFactory.buildModel(Object.assign(Object.assign({}, fdc3intentChannel), { displayMetadata: Object.assign(Object.assign({}, fdc3intentChannel.displayMetadata), { glueChannel }) }));
2004
+ }
2005
+ if (fdc3intentChannel.type !== "private") {
2006
+ return this.channelsFactory.buildModel(fdc3intentChannel);
2007
+ }
2008
+ yield this.glueEventsController.initializeCollaborateMethod();
2009
+ const channel = this.channelsController.buildPrivateChannel(fdc3intentChannel.id, commandId, false);
2010
+ channel.setCollaborator({ appId: glueIntentResult.handler.applicationName, instanceId: glueIntentResult.handler.instanceId }, commandId);
2011
+ const joinChannelArgs = {
2012
+ action: "joinPrivateChannel",
2013
+ correlationId: channel.id,
2014
+ collaborationObject: {
2015
+ channelId: channel.id
2016
+ }
2017
+ };
2018
+ yield this.glueController.invokeSystemMethod(joinChannelArgs, glueIntentResult.handler.instanceId);
1919
2019
  this.logger.info(`[${commandId}] - returning private channel`);
1920
- return channel;
2020
+ return channel.toApi();
1921
2021
  });
1922
2022
  }
1923
2023
  convertGlue42IntentToFDC3Intent(glueIntent) {
@@ -1952,15 +2052,23 @@
1952
2052
  throw new Error("Async handler function should return a promise that resolves to a Context or Channel");
1953
2053
  }
1954
2054
  getWrappedIntentHandler(handler) {
1955
- const wrappedHandler = (glue42Context) => __awaiter(this, void 0, void 0, function* () {
1956
- const handlerResult = yield handler(Object.assign(Object.assign({}, glue42Context.data), { type: glue42Context.type || "" }));
2055
+ const wrappedHandler = (glue42Context, caller) => __awaiter(this, void 0, void 0, function* () {
2056
+ const contextMetadata = caller
2057
+ ? {
2058
+ source: {
2059
+ appId: caller.application || caller.applicationName || "",
2060
+ instanceId: caller.instance
2061
+ }
2062
+ }
2063
+ : undefined;
2064
+ const handlerResult = yield handler(Object.assign(Object.assign({}, glue42Context.data), { type: glue42Context.type || "" }), contextMetadata);
1957
2065
  if (!handlerResult) {
1958
2066
  return;
1959
2067
  }
1960
2068
  const handlerResultType = this.getResultType(handlerResult);
1961
2069
  return handlerResultType === IntentHandlerResultTypes.Channel
1962
- ? extractChannelMetadata(handlerResult)
1963
- : handlerResult;
2070
+ ? { fdc3intentChannel: extractChannelMetadata(handlerResult) }
2071
+ : { fdc3intentContext: { contextType: handlerResult.type, payload: handlerResult } };
1964
2072
  });
1965
2073
  return wrappedHandler;
1966
2074
  }
@@ -2007,13 +2115,14 @@
2007
2115
  }
2008
2116
  }
2009
2117
 
2010
- var version = "2.1.1";
2118
+ var version = "2.1.3";
2011
2119
 
2012
2120
  class ApplicationsController {
2013
- constructor(glueController) {
2121
+ constructor(glueController, appsStateStore, glueEventsController) {
2014
2122
  this.glueController = glueController;
2015
- this.defaultContextListenerInvokedPromiseTimeout = 60000;
2016
- this.contextListenerInvokedPromises = {};
2123
+ this.appsStateStore = appsStateStore;
2124
+ this.glueEventsController = glueEventsController;
2125
+ this.defaultContextListenerInvokedPromiseTimeout = 120 * 1000;
2017
2126
  }
2018
2127
  get logger() {
2019
2128
  if (!this._logger) {
@@ -2031,6 +2140,7 @@
2031
2140
  throw { message: OpenError.AppNotFound, reason: `Cannot find targeted ${name} application` };
2032
2141
  }
2033
2142
  if (context) {
2143
+ yield this.glueEventsController.initializeCollaborateMethod();
2034
2144
  this.logger.info(`[${commandId}] - opening app ${app} with startup context`);
2035
2145
  return this.openAppWithContext(app, context);
2036
2146
  }
@@ -2146,41 +2256,39 @@
2146
2256
  }
2147
2257
  openAppWithContext(app, context) {
2148
2258
  return __awaiter(this, void 0, void 0, function* () {
2149
- const methodName = yield this.registerContextListenerInteropMethod();
2150
- const startContext = this.buildGlueStartContext(context, methodName);
2151
- const glueInst = yield app.start(startContext);
2152
- this.createContextListenerResponsePromise(glueInst, methodName);
2259
+ const guid = nanoid();
2260
+ const startContext = this.buildStartContext(context, guid);
2261
+ const wrappedPromise = this.createContextListenerWrappedPromise(app);
2262
+ this.appsStateStore.addOpenAppPromise(guid, wrappedPromise);
2153
2263
  try {
2154
- yield this.contextListenerInvokedPromises[glueInst.id].promise;
2155
- yield this.unregisterContextListenerPromise(glueInst.id);
2264
+ const glueInst = yield app.start(startContext);
2265
+ yield wrappedPromise.promise;
2266
+ this.appsStateStore.removeOpenAppPromise(guid);
2156
2267
  return this.parseGlueInstToAppIdentifier(glueInst);
2157
2268
  }
2158
2269
  catch (error) {
2159
- yield this.unregisterContextListenerPromise(glueInst.id);
2270
+ this.appsStateStore.removeOpenAppPromise(guid);
2160
2271
  throw { message: OpenError.AppTimeout, reason: typeof error === "string" ? error : JSON.stringify(error) };
2161
2272
  }
2162
2273
  });
2163
2274
  }
2164
- buildGlueStartContext(fdc3Context, responseMethodName) {
2275
+ buildStartContext(fdc3Context, guid) {
2276
+ const myInteropInstance = this.glueController.getMyInteropInstance();
2165
2277
  return {
2166
- meta: {
2167
- responseMethodName,
2168
- instance: this.glueController.interopInstance().instance
2169
- },
2170
- context: fdc3Context
2278
+ fdc3: {
2279
+ collaborationId: guid,
2280
+ openApp: {
2281
+ appId: myInteropInstance.application || myInteropInstance.applicationName || "",
2282
+ instanceId: myInteropInstance.instance
2283
+ },
2284
+ context: {
2285
+ contextType: fdc3Context.type,
2286
+ payload: fdc3Context
2287
+ }
2288
+ }
2171
2289
  };
2172
2290
  }
2173
- registerContextListenerInteropMethod() {
2174
- return __awaiter(this, void 0, void 0, function* () {
2175
- const methodName = this.buildInteropMethodName();
2176
- yield this.glueController.registerMethod(methodName, this.contextListenerResponseHandler.bind(this));
2177
- return methodName;
2178
- });
2179
- }
2180
- buildInteropMethodName() {
2181
- return `${responseInteropMethodPrefix}.${nanoid()}`;
2182
- }
2183
- createContextListenerResponsePromise(instance, methodName) {
2291
+ createContextListenerWrappedPromise(app) {
2184
2292
  let resolve = () => { };
2185
2293
  let reject = () => { };
2186
2294
  const promise = promisePlus(() => {
@@ -2188,50 +2296,32 @@
2188
2296
  resolve = res;
2189
2297
  reject = rej;
2190
2298
  });
2191
- }, this.defaultContextListenerInvokedPromiseTimeout, `Timeout of ${this.defaultContextListenerInvokedPromiseTimeout}ms hit waiting for application with appId: ${instance.application.name} and instanceId: ${instance.id} to register context listener`);
2192
- this.contextListenerInvokedPromises[instance.id] = { promise, resolve, reject, methodName };
2193
- }
2194
- contextListenerResponseHandler(args, callerId) {
2195
- const result = ContextListenerResponseDecoder.run(args);
2196
- if (!result.ok) {
2197
- const contextListenerPromise = this.contextListenerInvokedPromises[callerId.instance];
2198
- if (!contextListenerPromise) {
2199
- return;
2200
- }
2201
- contextListenerPromise.reject(`Method invoked with invalid argument - ${result.error.message}`);
2202
- return;
2203
- }
2204
- const contextListenerPromise = this.contextListenerInvokedPromises[callerId.instance];
2205
- if (!contextListenerPromise) {
2206
- return;
2207
- }
2208
- contextListenerPromise.resolve();
2209
- }
2210
- unregisterContextListenerPromise(instanceId) {
2211
- return __awaiter(this, void 0, void 0, function* () {
2212
- const { methodName } = this.contextListenerInvokedPromises[instanceId];
2213
- yield this.glueController.unregisterMethod(methodName);
2214
- delete this.contextListenerInvokedPromises[instanceId];
2215
- });
2299
+ }, this.defaultContextListenerInvokedPromiseTimeout, `Timeout of ${this.defaultContextListenerInvokedPromiseTimeout}ms hit waiting for application with appId: ${app.name} to register context listener`);
2300
+ return { promise, resolve, reject };
2216
2301
  }
2217
2302
  }
2218
2303
 
2219
2304
  class ChannelsController {
2220
- constructor(glueController, channelsStateStore, channelsParser, channelsFactory, channelsCallbackRegistry) {
2305
+ constructor(glueController, channelsStateStore, channelsParser, channelsFactory, glueEventsController) {
2221
2306
  this.glueController = glueController;
2222
2307
  this.channelsStateStore = channelsStateStore;
2223
2308
  this.channelsParser = channelsParser;
2224
2309
  this.channelsFactory = channelsFactory;
2225
- this.channelsCallbackRegistry = channelsCallbackRegistry;
2310
+ this.glueEventsController = glueEventsController;
2226
2311
  this.invokeContextHandlerWithStartupContext = true;
2227
2312
  this.initDonePromise = this.initialize();
2228
- this.initDonePromise.catch(() => { });
2313
+ this.initDonePromise.catch((err) => {
2314
+ var _a;
2315
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(err);
2316
+ });
2229
2317
  }
2230
- get logger() {
2231
- if (!this._logger) {
2232
- this._logger = this.glueController.initSubLogger("fdc3.channels.controller");
2233
- }
2234
- return this._logger;
2318
+ getStartupContext() {
2319
+ var _a, _b;
2320
+ return __awaiter(this, void 0, void 0, function* () {
2321
+ yield this.initDonePromise;
2322
+ const fdc3StartupContext = yield this.glueController.getMyWindowContext();
2323
+ return ((_b = (_a = fdc3StartupContext === null || fdc3StartupContext === void 0 ? void 0 : fdc3StartupContext.fdc3) === null || _a === void 0 ? void 0 : _a.context) === null || _b === void 0 ? void 0 : _b.payload) || null;
2324
+ });
2235
2325
  }
2236
2326
  addContextListener({ commandId, handler, contextType, channelId }) {
2237
2327
  var _a;
@@ -2269,14 +2359,14 @@
2269
2359
  return __awaiter(this, void 0, void 0, function* () {
2270
2360
  yield this.initDonePromise;
2271
2361
  this.logger.info(`[${commandId}] - getOrCreateChannel() invoked for channel with id ${channelId}`);
2272
- const isPrivateChannel = this.isPrivateChannel(channelId);
2273
- if (isPrivateChannel) {
2274
- throw { message: ChannelError.AccessDenied, reason: "Cannot retrieve a private channel" };
2275
- }
2276
2362
  const isUserChannel = this.isUserChannel(channelId);
2277
2363
  if (isUserChannel) {
2278
2364
  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" };
2279
2365
  }
2366
+ const isPrivateChannel = this.channelsStateStore.getPrivateChannelById(channelId);
2367
+ if (isPrivateChannel) {
2368
+ throw { message: ChannelError.AccessDenied, reason: "Cannot retrieve a private channel" };
2369
+ }
2280
2370
  return this.getOrCreateAppChannel(commandId, channelId);
2281
2371
  });
2282
2372
  }
@@ -2354,26 +2444,28 @@
2354
2444
  return __awaiter(this, void 0, void 0, function* () {
2355
2445
  yield this.initDonePromise;
2356
2446
  this.logger.info(`[${commandId}] - createPrivateChannel() invoked`);
2357
- const creatorId = this.glueController.getMyInteropInstanceId();
2358
- const channel = this.buildChannel(ChannelTypes.Private);
2359
- yield this.glueController.updateContext(channel.id, { creatorId });
2360
- this.logger.info(`[${commandId}] - private channel with id ${channel.id} created`);
2361
- return channel;
2447
+ const channelId = `${PrivateChannelPrefix}${nanoid()}`;
2448
+ yield this.glueEventsController.initializeCollaborateMethod();
2449
+ const pc = this.buildPrivateChannel(channelId, commandId, true);
2450
+ return pc.toApi();
2362
2451
  });
2363
2452
  }
2364
- announceDisconnect(commandId, channelId, instanceId) {
2453
+ removePrivateChannelFromStoreById(id) {
2365
2454
  return __awaiter(this, void 0, void 0, function* () {
2366
- yield this.initDonePromise;
2367
- this.logger.info(`[${commandId}] - disconnect() invoked on channel with id ${channelId}`);
2368
- yield this.glueController.updateContext(channelId, { disconnected: true });
2369
- this.logger.info(`[${commandId}] - glue context for ${channelId} updated with disconnected flag`);
2370
- const closedInstanceId = instanceId || this.glueController.getMyInteropInstanceId();
2371
- const targetInstance = yield this.getOtherInstanceIdFromClosedOne(channelId, closedInstanceId);
2372
- const replayContextTypes = yield this.getContextTypesForPrivateChannel(channelId);
2373
- this.logger.info(`[${commandId}] - invoking onDisconnect callback for instance ${targetInstance}`);
2374
- this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnDisconnect, { clientId: targetInstance, channelId, replayContextTypes });
2455
+ this.channelsStateStore.removePrivateChannelById(id);
2456
+ });
2457
+ }
2458
+ invokeSystemMethod(args, target) {
2459
+ return __awaiter(this, void 0, void 0, function* () {
2460
+ if (!target) {
2461
+ return;
2462
+ }
2463
+ return this.glueController.invokeSystemMethod(args, target);
2375
2464
  });
2376
2465
  }
2466
+ getMyServerInstance() {
2467
+ return this.glueController.getMyInteropInstance();
2468
+ }
2377
2469
  addClientToPrivateChannel(commandId, channelId, clientId) {
2378
2470
  return __awaiter(this, void 0, void 0, function* () {
2379
2471
  this.logger.info(`[${commandId}] - client with id ${clientId} added to private channel with id ${channelId}`);
@@ -2387,28 +2479,22 @@
2387
2479
  return !!context.disconnected;
2388
2480
  });
2389
2481
  }
2390
- registerOnInstanceStopped({ commandId, channelId }) {
2391
- this.logger.info(`[${commandId}] - registering onInstanceStopped callback for channel with id ${channelId}`);
2392
- const handler = (instance) => __awaiter(this, void 0, void 0, function* () {
2393
- const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2394
- if (instance.id !== clientId && instance.id !== creatorId) {
2395
- return;
2396
- }
2397
- this.logger.info(`[${commandId}] - calling onDisconnect callback for channel with id ${channelId}`);
2398
- yield this.announceDisconnect(commandId, channelId, instance.id);
2399
- });
2482
+ subscribeOnInstanceStop(channelId, handler, commandId) {
2483
+ this.logger.info(`[${commandId}] - subscribing onInstanceStopped callback for channel with id ${channelId}`);
2400
2484
  return this.glueController.registerOnInstanceStopped(handler.bind(this));
2401
2485
  }
2402
- addPrivateChannelEvent({ commandId, action, channelId, handler }) {
2403
- return __awaiter(this, void 0, void 0, function* () {
2404
- this.logger.info(`[${commandId}] - registering callback for ${action} event in channel with id ${channelId}`);
2405
- let replayArgs;
2406
- const targetInstanceId = yield this.getTargetedInstanceId(channelId);
2407
- if (action === PrivateChannelEventMethods.OnAddContextListener && targetInstanceId) {
2408
- replayArgs = yield this.getContextTypesForPrivateChannel(channelId);
2409
- }
2410
- return this.channelsCallbackRegistry.add({ action, channelId, handler, replayArgs });
2411
- });
2486
+ buildPrivateChannel(channelId, commandId, isCreator) {
2487
+ const logger = this.glueController.initSubLogger(channelId);
2488
+ const channel = this.buildChannel(ChannelTypes.Private, { id: channelId, logger, isCreator });
2489
+ this.logger.info(`[${commandId}] - private channel with id ${channelId} created. Adding it to the store`);
2490
+ this.channelsStateStore.addPrivateChannel(channel);
2491
+ return channel;
2492
+ }
2493
+ get logger() {
2494
+ if (!this._logger) {
2495
+ this._logger = this.glueController.initSubLogger("fdc3.channels.controller");
2496
+ }
2497
+ return this._logger;
2412
2498
  }
2413
2499
  initialize() {
2414
2500
  return __awaiter(this, void 0, void 0, function* () {
@@ -2457,39 +2543,43 @@
2457
2543
  return __awaiter(this, void 0, void 0, function* () {
2458
2544
  const myWindow = this.glueController.getMyWindow();
2459
2545
  if (!myWindow) {
2460
- this.logger.log(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
2546
+ this.logger.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
2461
2547
  this.invokeContextHandlerWithStartupContext = false;
2462
2548
  return;
2463
2549
  }
2464
2550
  const windowContext = yield myWindow.getContext();
2465
- if (!isValidNonEmptyObject(windowContext)) {
2466
- this.logger.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
2551
+ if (!windowContext) {
2552
+ this.logger.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
2467
2553
  this.invokeContextHandlerWithStartupContext = false;
2468
2554
  return;
2469
2555
  }
2470
- const { context, meta } = windowContext;
2471
- const isSameContextType = contextType ? (context === null || context === void 0 ? void 0 : context.type) === contextType : true;
2472
- if (!isSameContextType || !meta) {
2473
- this.logger.info(`[${commandId}] - addContextListener handler won't be invoked`);
2556
+ if (!isValidNonEmptyObject(windowContext) || !windowContext.fdc3) {
2557
+ this.logger.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
2558
+ this.invokeContextHandlerWithStartupContext = false;
2474
2559
  return;
2475
2560
  }
2476
- this.logger.info(`[${commandId}] - invoking addContextListener handler with startup context`);
2477
- handler(context);
2478
- this.invokeContextHandlerWithStartupContext = false;
2479
- const { responseMethodName, instance } = meta;
2480
- const responseMethodExists = this.doesServerMethodExist(responseMethodName, instance);
2481
- if (!responseMethodExists) {
2482
- this.logger.info(`[${commandId}] - response method for instance ${instance} does not exist anymore. returning`);
2561
+ yield this.glueEventsController.initializeCollaborateMethod();
2562
+ FDC3StartupContextDecoder.runWithException(windowContext);
2563
+ const { fdc3 } = windowContext;
2564
+ this.logger.trace(`[${commandId}] - received FDC3 startup context from ${JSON.stringify(fdc3.openApp)} for contextType ${fdc3.context.contextType}`);
2565
+ const isSameContextType = contextType ? fdc3.context.contextType === contextType : true;
2566
+ if (!isSameContextType) {
2567
+ this.logger.info(`[${commandId}] - addContextListener handler won't be invoked for contextType ${contextType} for startup context with type: ${fdc3.context.contextType}`);
2483
2568
  return;
2484
2569
  }
2485
- this.logger.info(`[${commandId}] - invoking response method for instance ${instance}`);
2486
- yield this.glueController.invokeMethod(responseMethodName, instance, { listenerInvoked: true });
2570
+ this.logger.info(`[${commandId}] - invoking addContextListener handler with startup context with type ${fdc3.context.contextType}`);
2571
+ try {
2572
+ handler(fdc3.context.payload, { source: fdc3.openApp });
2573
+ }
2574
+ catch (error) {
2575
+ this.logger.error(typeof error === "string" ? error : error.message ? JSON.stringify(error.message) : JSON.stringify(error));
2576
+ }
2577
+ this.invokeContextHandlerWithStartupContext = false;
2578
+ this.logger.trace(`[${commandId}] - invoking response method to with target ${JSON.stringify(fdc3.openApp)}`);
2579
+ yield this.invokeSystemMethod({ action: "startupContextOpened", correlationId: fdc3.collaborationId }, fdc3.openApp.instanceId);
2580
+ this.logger.trace(`[${commandId}] - system method invocation success for 'startupContextOpened' heard`);
2487
2581
  });
2488
2582
  }
2489
- doesServerMethodExist(methodName, instance) {
2490
- const serversForMethodName = this.glueController.getInteropServers({ name: methodName });
2491
- return !!serversForMethodName.find(server => server.instance === instance);
2492
- }
2493
2583
  getOrCreateAppChannel(commandId, channelId) {
2494
2584
  return __awaiter(this, void 0, void 0, function* () {
2495
2585
  const exists = this.doesAppChannelExist(channelId);
@@ -2498,7 +2588,8 @@
2498
2588
  yield this.glueController.updateContext(channelId, {});
2499
2589
  }
2500
2590
  this.logger.info(`[${commandId}] - returning app channel with id ${channelId}`);
2501
- return this.buildChannel(ChannelTypes.App, { id: channelId });
2591
+ const logger = this.glueController.initSubLogger(`app.channel.${channelId}`);
2592
+ return this.buildChannel(ChannelTypes.App, { id: channelId, logger });
2502
2593
  });
2503
2594
  }
2504
2595
  doesAppChannelExist(name) {
@@ -2510,12 +2601,6 @@
2510
2601
  }
2511
2602
  return !!this.channelsStateStore.userChannels[channelId];
2512
2603
  }
2513
- isPrivateChannel(channelId) {
2514
- return channelId.includes(PrivateChannelPrefix) && this.glueController.getAllContexts().some((ctxName) => ctxName === channelId);
2515
- }
2516
- buildChannel(type, data) {
2517
- return this.channelsFactory.buildModel(Object.assign(Object.assign({ type }, data), { isChannel: true }));
2518
- }
2519
2604
  broadcastByChannelId(commandId, channelId, context) {
2520
2605
  return __awaiter(this, void 0, void 0, function* () {
2521
2606
  const isUserChannel = this.isUserChannel(channelId);
@@ -2550,21 +2635,6 @@
2550
2635
  }
2551
2636
  };
2552
2637
  }
2553
- if (channelType === ChannelTypes.Private) {
2554
- this.logger.info(`[${commandId}] - subscribing for fdc3 private channel with id ${channelId} (underlying glue context with same name)`);
2555
- const contextsUnsubscribe = yield this.glueController.contextsSubscribe(channelId, subHandler);
2556
- yield this.addContextTypeInPrivateChannelContext(channelId, contextType);
2557
- const targetInstance = yield this.getTargetedInstanceId(channelId);
2558
- const unsubscribe = () => {
2559
- this.logger.info(`[${commandId}] - unsubscribe invoked for private channel with id ${channelId}`);
2560
- contextsUnsubscribe();
2561
- this.logger.info(`[${commandId}] - invoking onUnsubscribe handler for private channel with id ${channelId}`);
2562
- this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnUnsubscribe, { channelId, clientId: targetInstance, contextType });
2563
- };
2564
- this.logger.info(`[${commandId}] - invoking onAddContextListener handler for private channel with id ${channelId}`);
2565
- this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnAddContextListener, { channelId: channelId, clientId: targetInstance, contextType });
2566
- return { unsubscribe };
2567
- }
2568
2638
  throw { message: ChannelError.AccessDenied, reason: "Cannot add a context listener on an invalid channel" };
2569
2639
  });
2570
2640
  }
@@ -2593,56 +2663,21 @@
2593
2663
  if (isUser) {
2594
2664
  return ChannelTypes.User;
2595
2665
  }
2596
- const isPrivate = this.isPrivateChannel(channelId);
2597
- if (isPrivate) {
2598
- return ChannelTypes.Private;
2599
- }
2600
2666
  const isApp = this.doesAppChannelExist(channelId);
2601
2667
  if (isApp) {
2602
2668
  return ChannelTypes.App;
2603
2669
  }
2604
2670
  throw { message: ChannelError.NoChannelFound, reason: `Channel with id: ${channelId} does not exist` };
2605
2671
  }
2606
- getTargetedInstanceId(channelId) {
2607
- return __awaiter(this, void 0, void 0, function* () {
2608
- const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2609
- const myId = this.glueController.getMyInteropInstanceId();
2610
- return myId === clientId ? creatorId : clientId;
2611
- });
2612
- }
2613
- getOtherInstanceIdFromClosedOne(channelId, closedInstanceId) {
2614
- return __awaiter(this, void 0, void 0, function* () {
2615
- const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2616
- return closedInstanceId === clientId
2617
- ? creatorId
2618
- : clientId;
2619
- });
2620
- }
2621
- invokeSystemMethod(clientId, action, payload) {
2622
- if (clientId) {
2623
- this.glueController.invokeSystemMethod({ action, payload });
2624
- }
2625
- }
2626
- addContextTypeInPrivateChannelContext(channelId, contextType) {
2627
- return __awaiter(this, void 0, void 0, function* () {
2628
- const currentContext = yield this.glueController.getContext(channelId);
2629
- const updatedTypes = currentContext.contextListenerTypes ? [...currentContext.contextListenerTypes, contextType] : [contextType];
2630
- return this.glueController.updateContext(channelId, Object.assign(Object.assign({}, currentContext), { contextListenerTypes: updatedTypes }));
2631
- });
2632
- }
2633
- getContextTypesForPrivateChannel(channelId) {
2634
- return __awaiter(this, void 0, void 0, function* () {
2635
- const ctx = yield this.glueController.getContext(channelId);
2636
- return ctx.contextListenerTypes;
2637
- });
2672
+ buildChannel(type, data) {
2673
+ return this.channelsFactory.buildModel(Object.assign({ type }, data));
2638
2674
  }
2639
2675
  }
2640
2676
 
2641
2677
  class EventReceiver {
2642
- constructor(glueController, eventDispatcher, eventsController) {
2678
+ constructor(glueController, eventDispatcher) {
2643
2679
  this.glueController = glueController;
2644
2680
  this.eventDispatcher = eventDispatcher;
2645
- this.eventsController = eventsController;
2646
2681
  this.glueResponseReceived = false;
2647
2682
  this.glueInitialized = false;
2648
2683
  this.events = {
@@ -2688,7 +2723,6 @@
2688
2723
  }
2689
2724
  window.removeEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
2690
2725
  this.glueController.initialize(glue);
2691
- yield this.eventsController.initialize();
2692
2726
  this.eventDispatcher.fireFdc3Ready();
2693
2727
  this.glueInitialized = true;
2694
2728
  });
@@ -2700,16 +2734,17 @@
2700
2734
  this._currentChannel = null;
2701
2735
  this._userChannels = {};
2702
2736
  this._fdc3ChannelIdsToGlueChannelNames = {};
2737
+ this._privateChannels = {};
2703
2738
  }
2704
2739
  get currentChannel() {
2705
2740
  return this._currentChannel;
2706
2741
  }
2707
- get userChannels() {
2708
- return this._userChannels;
2709
- }
2710
2742
  set currentChannel(newChannelValue) {
2711
2743
  this._currentChannel = newChannelValue;
2712
2744
  }
2745
+ get userChannels() {
2746
+ return this._userChannels;
2747
+ }
2713
2748
  addUserChannel(channel) {
2714
2749
  this._userChannels[channel.id] = channel;
2715
2750
  }
@@ -2723,140 +2758,14 @@
2723
2758
  const [key] = Object.entries(this._fdc3ChannelIdsToGlueChannelNames).find(([_, value]) => value === glueChannelName);
2724
2759
  return key;
2725
2760
  }
2726
- }
2727
-
2728
- class PrivateChannel {
2729
- constructor(channelsController, channelId) {
2730
- this.channelsController = channelsController;
2731
- this.type = ChannelTypes.Private;
2732
- this.id = channelId || `${PrivateChannelPrefix}${nanoid()}`;
2733
- this.unsubFromInstanceStopped = this.channelsController.registerOnInstanceStopped({ commandId: generateCommandId(), channelId: this.id });
2734
- }
2735
- toApi() {
2736
- const api = {
2737
- id: this.id,
2738
- type: this.type,
2739
- displayMetadata: this.displayMetadata,
2740
- broadcast: this.broadcast.bind(this),
2741
- getCurrentContext: this.getCurrentContext.bind(this),
2742
- addContextListener: this.addContextListener.bind(this),
2743
- onAddContextListener: this.onAddContextListener.bind(this),
2744
- onUnsubscribe: this.onUnsubscribe.bind(this),
2745
- onDisconnect: this.onDisconnect.bind(this),
2746
- disconnect: this.disconnect.bind(this),
2747
- };
2748
- return api;
2749
- }
2750
- broadcast(context) {
2751
- return __awaiter(this, void 0, void 0, function* () {
2752
- const commandId = generateCommandId();
2753
- const isDisconnected = yield this.channelsController.isPrivateChannelDisconnected({ commandId, channelId: this.id });
2754
- if (isDisconnected) {
2755
- throw { message: ChannelError.AccessDenied, reason: "Channel has disconnected - broadcast is no longer available" };
2756
- }
2757
- contextDecoder.runWithException(context);
2758
- return this.channelsController.broadcast(commandId, context, this.id);
2759
- });
2761
+ addPrivateChannel(privateChannel) {
2762
+ this._privateChannels[privateChannel.id] = privateChannel;
2760
2763
  }
2761
- getCurrentContext(contextType) {
2762
- return __awaiter(this, void 0, void 0, function* () {
2763
- optionalNonEmptyStringDecoder.runWithException(contextType);
2764
- return this.channelsController.getContextForChannel({ commandId: generateCommandId(), channelId: this.id, contextType });
2765
- });
2764
+ getPrivateChannelById(id) {
2765
+ return this._privateChannels[id];
2766
2766
  }
2767
- addContextListener(contextType, handler) {
2768
- return __awaiter(this, arguments, void 0, function* () {
2769
- if (arguments.length === 1) {
2770
- if (typeof contextType !== "function") {
2771
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
2772
- }
2773
- return this.channelsController.addContextListener({ commandId: generateCommandId(), handler: contextType, channelId: this.id });
2774
- }
2775
- const contextTypeDecoder = optionalNonEmptyStringDecoder.runWithException(contextType);
2776
- if (typeof handler !== "function") {
2777
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
2778
- }
2779
- return this.channelsController.addContextListener({
2780
- commandId: generateCommandId(),
2781
- contextType: contextTypeDecoder,
2782
- channelId: this.id,
2783
- handler,
2784
- });
2785
- });
2786
- }
2787
- onAddContextListener(handler) {
2788
- if (typeof handler !== "function") {
2789
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2790
- }
2791
- const unsub = this.channelsController.addPrivateChannelEvent({
2792
- commandId: generateCommandId(),
2793
- action: PrivateChannelEventMethods.OnAddContextListener,
2794
- channelId: this.id,
2795
- handler
2796
- });
2797
- return AsyncListener(unsub);
2798
- }
2799
- onUnsubscribe(handler) {
2800
- if (typeof handler !== "function") {
2801
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2802
- }
2803
- const unsub = this.channelsController.addPrivateChannelEvent({
2804
- commandId: generateCommandId(),
2805
- action: PrivateChannelEventMethods.OnUnsubscribe,
2806
- channelId: this.id,
2807
- handler
2808
- });
2809
- return AsyncListener(unsub);
2810
- }
2811
- onDisconnect(handler) {
2812
- if (typeof handler !== "function") {
2813
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2814
- }
2815
- const unsub = this.channelsController.addPrivateChannelEvent({
2816
- commandId: generateCommandId(),
2817
- action: PrivateChannelEventMethods.OnDisconnect,
2818
- channelId: this.id,
2819
- handler
2820
- });
2821
- return AsyncListener(unsub);
2822
- }
2823
- disconnect() {
2824
- return __awaiter(this, void 0, void 0, function* () {
2825
- yield this.channelsController.announceDisconnect(generateCommandId(), this.id);
2826
- this.unsubFromInstanceStopped();
2827
- });
2828
- }
2829
- }
2830
-
2831
- class ChannelsFactory {
2832
- constructor(createUserChannelFn, createAppChannel, createPrivateChannel) {
2833
- this.createUserChannelFn = createUserChannelFn;
2834
- this.createAppChannel = createAppChannel;
2835
- this.createPrivateChannel = createPrivateChannel;
2836
- }
2837
- buildModel(data) {
2838
- const { type } = data;
2839
- if (type === ChannelTypes.User) {
2840
- return this.buildUserChannel(data.displayMetadata.glueChannel);
2841
- }
2842
- else if (type === ChannelTypes.App) {
2843
- return this.buildAppChannel(data.id);
2844
- }
2845
- else if (type === ChannelTypes.Private) {
2846
- return this.buildPrivateChannel(data.id);
2847
- }
2848
- else {
2849
- throw new Error("Pass one of the supported channel types: user, app, private");
2850
- }
2851
- }
2852
- buildUserChannel(data) {
2853
- return this.createUserChannelFn(data);
2854
- }
2855
- buildAppChannel(channelId) {
2856
- return this.createAppChannel(channelId);
2857
- }
2858
- buildPrivateChannel(channelId) {
2859
- return this.createPrivateChannel(channelId);
2767
+ removePrivateChannelById(id) {
2768
+ delete this._privateChannels[id];
2860
2769
  }
2861
2770
  }
2862
2771
 
@@ -2977,36 +2886,345 @@
2977
2886
  createRegistry.default = createRegistry;
2978
2887
  var lib = createRegistry;
2979
2888
 
2980
- class ChannelsCallbackRegistry {
2981
- constructor() {
2889
+ class PrivateChannel {
2890
+ constructor(channelsController, logger, channelId, isCreator) {
2891
+ this.channelsController = channelsController;
2892
+ this.logger = logger;
2893
+ this.isCreator = isCreator;
2894
+ this.type = ChannelTypes.Private;
2895
+ this.disconnected = false;
2896
+ this.broadcastedContexts = {};
2897
+ this.collaboratorListenerTypes = [];
2898
+ this.myListenerTypesBeforeBound = [];
2982
2899
  this.registry = lib();
2900
+ this.id = channelId;
2901
+ const myServerInstance = this.channelsController.getMyServerInstance();
2902
+ this.myAppMetadata = { source: { appId: myServerInstance.applicationName, instanceId: myServerInstance.instance } };
2983
2903
  }
2984
- add({ action, channelId, handler, replayArgs }) {
2985
- return this.registry.add(`${action}-${channelId}`, handler, replayArgs);
2904
+ toApi() {
2905
+ const api = {
2906
+ id: this.id,
2907
+ type: this.type,
2908
+ displayMetadata: this.displayMetadata,
2909
+ broadcast: this.broadcast.bind(this),
2910
+ getCurrentContext: this.getCurrentContext.bind(this),
2911
+ addContextListener: this.addContextListener.bind(this),
2912
+ onAddContextListener: this.onAddContextListener.bind(this),
2913
+ onUnsubscribe: this.onUnsubscribe.bind(this),
2914
+ onDisconnect: this.onDisconnect.bind(this),
2915
+ disconnect: this.disconnect.bind(this),
2916
+ };
2917
+ return api;
2918
+ }
2919
+ getCollaborator() {
2920
+ return this.collaborator;
2921
+ }
2922
+ setCollaborator(collaborator, commandId) {
2923
+ if (this.collaborator && this.collaborator.instanceId !== collaborator.instanceId) {
2924
+ throw new Error(`There's already a collaborator for private channel with id ${this.id}`);
2925
+ }
2926
+ this.collaborator = collaborator;
2927
+ this.subscribeForCollaboratorInstanceStop(commandId);
2928
+ }
2929
+ handleCollaboratorJoin(collaborator, commandId) {
2930
+ return __awaiter(this, void 0, void 0, function* () {
2931
+ this.setCollaborator(collaborator, commandId);
2932
+ yield Promise.all(this.myListenerTypesBeforeBound.map((contextType) => {
2933
+ var _a;
2934
+ const listenerAddedArgs = {
2935
+ action: "addedContextListenerOnPrivateChannel",
2936
+ correlationId: this.id,
2937
+ collaborationObject: {
2938
+ channelId: this.id,
2939
+ contextType: contextType || undefined
2940
+ }
2941
+ };
2942
+ this.logger.trace(`[${commandId}] - announcing ${"addedContextListenerOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
2943
+ return this.channelsController.invokeSystemMethod(listenerAddedArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
2944
+ })).catch((err) => this.logger.error(err));
2945
+ });
2946
+ }
2947
+ handleCollaboratorBroadcast(context, metadata, commandId) {
2948
+ this.logger.trace(`[${commandId}] - heard context with type ${context.type} broadcasted on the channel`);
2949
+ this.lastBroadcastedContextType = context.type;
2950
+ this.broadcastedContexts[context.type] = { context, metadata };
2951
+ this.logger.trace(`[${commandId}] - invoking all context listeners`);
2952
+ this.registry.execute(PrivateChannelEventMethods.ListenerAdded, context, metadata);
2953
+ }
2954
+ handleCollaboratorAddContextListener(contextType, commandId) {
2955
+ this.logger.trace(`[${commandId}] - heard collaborator added context listener for type ${contextType}`);
2956
+ this.collaboratorListenerTypes.push(contextType);
2957
+ this.registry.execute(PrivateChannelEventMethods.OnAddContextListener, contextType);
2958
+ }
2959
+ handleCollaboratorRemovedListener(contextType, commandId) {
2960
+ this.logger.trace(`[${commandId}] - heard collaborator removed context listener with type ${contextType}`);
2961
+ const index = this.collaboratorListenerTypes.indexOf(contextType);
2962
+ this.collaboratorListenerTypes.splice(index, 1);
2963
+ this.registry.execute(PrivateChannelEventMethods.OnUnsubscribe, contextType);
2964
+ }
2965
+ handleCollaboratorDisconnect() {
2966
+ this.disconnected = true;
2967
+ this.collaboratorListenerTypes.forEach((contextType) => this.registry.execute(PrivateChannelEventMethods.OnUnsubscribe, contextType));
2968
+ this.registry.execute(PrivateChannelEventMethods.OnDisconnect);
2969
+ }
2970
+ announceJoin(targetInstance, commandId) {
2971
+ return __awaiter(this, void 0, void 0, function* () {
2972
+ const joinChannelArgs = {
2973
+ action: "joinPrivateChannel",
2974
+ correlationId: this.id,
2975
+ collaborationObject: {
2976
+ channelId: this.id
2977
+ }
2978
+ };
2979
+ this.logger.trace(`[${commandId}] - announcing ${"joinPrivateChannel"} to target instance with id ${JSON.stringify(targetInstance)}`);
2980
+ yield this.channelsController.invokeSystemMethod(joinChannelArgs, targetInstance);
2981
+ this.logger.trace(`[${commandId}] - collaborator received ${"joinPrivateChannel"} action`);
2982
+ });
2983
+ }
2984
+ broadcast(context) {
2985
+ var _a;
2986
+ return __awaiter(this, void 0, void 0, function* () {
2987
+ const commandId = generateCommandId();
2988
+ this.ensureAlive(commandId);
2989
+ this.ensureBound(commandId, "broadcast");
2990
+ contextDecoder.runWithException(context);
2991
+ this.lastBroadcastedContextType = context.type;
2992
+ this.broadcastedContexts[context.type] = { context, metadata: this.myAppMetadata };
2993
+ const broadcastArgs = {
2994
+ action: "publishOnPrivateChannel",
2995
+ correlationId: this.id,
2996
+ collaborationObject: {
2997
+ channelId: this.id,
2998
+ contextType: context.type,
2999
+ payload: context
3000
+ }
3001
+ };
3002
+ this.logger.trace(`[${commandId}] - announcing ${"publishOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
3003
+ yield this.channelsController.invokeSystemMethod(broadcastArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3004
+ this.logger.trace(`[${commandId}] - collaborator received context for action ${"publishOnPrivateChannel"}`);
3005
+ });
3006
+ }
3007
+ getCurrentContext(contextType) {
3008
+ return __awaiter(this, void 0, void 0, function* () {
3009
+ const commandId = generateCommandId();
3010
+ this.ensureAlive(commandId);
3011
+ this.logger.trace(`[${commandId}] - getCurrentContext invoked ${contextType ? `with contextType ${contextType}` : ""}`);
3012
+ optionalNonEmptyStringDecoder.runWithException(contextType);
3013
+ if (!contextType && !this.lastBroadcastedContextType) {
3014
+ return null;
3015
+ }
3016
+ const searchedType = contextType || this.lastBroadcastedContextType;
3017
+ this.logger.trace(`[${commandId}] - Returning context with type ${searchedType}`);
3018
+ return this.broadcastedContexts[searchedType].context;
3019
+ });
2986
3020
  }
2987
- invoke(action, argumentObj) {
2988
- const { channelId, contextType } = argumentObj;
2989
- this.registry.execute(`${action}-${channelId}`, contextType);
3021
+ addContextListener(contextType, handler) {
3022
+ var _a;
3023
+ return __awaiter(this, void 0, void 0, function* () {
3024
+ const commandId = generateCommandId();
3025
+ this.ensureAlive(commandId);
3026
+ optionalNonEmptyStringDecoder.runWithException(contextType);
3027
+ if (typeof handler !== "function") {
3028
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
3029
+ }
3030
+ this.logger.trace(`[${commandId}] - adding subscription for broadcasted contexts with type: ${contextType}`);
3031
+ const subHandler = (data, metadata) => {
3032
+ if (contextType) {
3033
+ if (data.type === contextType) {
3034
+ handler(data, metadata);
3035
+ }
3036
+ return;
3037
+ }
3038
+ handler(data, metadata);
3039
+ };
3040
+ const lastBroadcastedContextPerType = this.retrieveLatestBroadcastedContextPerType(contextType);
3041
+ const replayArgs = lastBroadcastedContextPerType ? [[lastBroadcastedContextPerType.context, lastBroadcastedContextPerType.metadata]] : undefined;
3042
+ const unsub = this.registry.add(PrivateChannelEventMethods.ListenerAdded, subHandler, replayArgs);
3043
+ if (this.collaborator) {
3044
+ const listenerAddedArgs = {
3045
+ action: "addedContextListenerOnPrivateChannel",
3046
+ correlationId: this.id,
3047
+ collaborationObject: {
3048
+ channelId: this.id,
3049
+ contextType: contextType || undefined
3050
+ }
3051
+ };
3052
+ this.logger.trace(`[${commandId}] - announcing ${"addedContextListenerOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
3053
+ yield this.channelsController.invokeSystemMethod(listenerAddedArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3054
+ this.logger.trace(`[${commandId}] - collaborator received action ${"addedContextListenerOnPrivateChannel"}`);
3055
+ }
3056
+ else {
3057
+ this.myListenerTypesBeforeBound.push(contextType);
3058
+ }
3059
+ const unsubscribe = this.getAddContextListenerUnsub(unsub, contextType, commandId);
3060
+ return AsyncListener(unsubscribe);
3061
+ });
3062
+ }
3063
+ retrieveLatestBroadcastedContextPerType(contextType) {
3064
+ if (!contextType && !this.lastBroadcastedContextType) {
3065
+ return;
3066
+ }
3067
+ if (!contextType && this.lastBroadcastedContextType) {
3068
+ return {
3069
+ context: this.broadcastedContexts[this.lastBroadcastedContextType].context,
3070
+ metadata: this.broadcastedContexts[this.lastBroadcastedContextType].metadata
3071
+ };
3072
+ }
3073
+ return this.broadcastedContexts[contextType];
3074
+ }
3075
+ getAddContextListenerUnsub(unsub, contextType, commandId) {
3076
+ return () => __awaiter(this, void 0, void 0, function* () {
3077
+ var _a;
3078
+ unsub();
3079
+ if (!this.collaborator) {
3080
+ const index = this.myListenerTypesBeforeBound.indexOf(contextType);
3081
+ this.myListenerTypesBeforeBound.splice(index, 1);
3082
+ return;
3083
+ }
3084
+ const unsubArgs = {
3085
+ action: "removedContextListenerOnPrivateChannel",
3086
+ correlationId: this.id,
3087
+ collaborationObject: {
3088
+ channelId: this.id,
3089
+ contextType: contextType || undefined
3090
+ }
3091
+ };
3092
+ this.logger.trace(`[${commandId}] - announcing unsubscribe from context listener for type ${contextType}`);
3093
+ yield this.channelsController.invokeSystemMethod(unsubArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3094
+ this.logger.trace(`[${commandId}] - collaborator heard ${"removedContextListenerOnPrivateChannel"}`);
3095
+ });
3096
+ }
3097
+ onAddContextListener(handler) {
3098
+ if (typeof handler !== "function") {
3099
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
3100
+ }
3101
+ const commandId = generateCommandId();
3102
+ this.ensureAlive(commandId);
3103
+ const unsub = this.registry.add(PrivateChannelEventMethods.OnAddContextListener, handler, this.collaboratorListenerTypes);
3104
+ return AsyncListener(unsub);
3105
+ }
3106
+ onUnsubscribe(handler) {
3107
+ if (typeof handler !== "function") {
3108
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
3109
+ }
3110
+ const commandId = generateCommandId();
3111
+ this.ensureAlive(commandId);
3112
+ const unsub = this.registry.add(PrivateChannelEventMethods.OnUnsubscribe, handler);
3113
+ return AsyncListener(unsub);
3114
+ }
3115
+ onDisconnect(handler) {
3116
+ if (typeof handler !== "function") {
3117
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
3118
+ }
3119
+ const commandId = generateCommandId();
3120
+ this.ensureAlive(commandId);
3121
+ const unsub = this.registry.add(PrivateChannelEventMethods.OnDisconnect, handler);
3122
+ return AsyncListener(unsub);
3123
+ }
3124
+ disconnect() {
3125
+ var _a;
3126
+ return __awaiter(this, void 0, void 0, function* () {
3127
+ const commandId = generateCommandId();
3128
+ if (this.isCreator && !this.collaborator) {
3129
+ this.disconnected = true;
3130
+ return;
3131
+ }
3132
+ this.ensureAlive(commandId);
3133
+ this.ensureBound(commandId, "disconnect");
3134
+ this.logger.trace(`[${commandId}] - disconnect invoked`);
3135
+ this.disconnected = true;
3136
+ this.logger.trace(`[${commandId}] - announcing ${"disconnectedFromPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
3137
+ const disconnectArgs = {
3138
+ action: "disconnectedFromPrivateChannel",
3139
+ correlationId: this.id,
3140
+ collaborationObject: {
3141
+ channelId: this.id
3142
+ }
3143
+ };
3144
+ this.channelsController.removePrivateChannelFromStoreById(this.id);
3145
+ yield this.channelsController.invokeSystemMethod(disconnectArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3146
+ this.logger.trace(`[${commandId}] - collaborator received action ${"disconnectedFromPrivateChannel"}`);
3147
+ if (this.unsubFromInstanceStopped) {
3148
+ this.unsubFromInstanceStopped();
3149
+ }
3150
+ });
3151
+ }
3152
+ ensureAlive(commandId) {
3153
+ if (!this.disconnected) {
3154
+ return;
3155
+ }
3156
+ const errorMsg = "Channel is disconnected - operation is no longer available";
3157
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3158
+ throw { message: ChannelError.AccessDenied, reason: errorMsg };
3159
+ }
3160
+ ensureBound(commandId, operation) {
3161
+ if (this.collaborator) {
3162
+ return;
3163
+ }
3164
+ const errorMsg = `There's no collaborator on the other side of the channel - operation ${operation} is unavailable`;
3165
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3166
+ throw { message: ChannelError.AccessDenied, reason: errorMsg };
3167
+ }
3168
+ subscribeForCollaboratorInstanceStop(commandId) {
3169
+ const handler = (instance) => {
3170
+ var _a;
3171
+ if (instance.id !== ((_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId)) {
3172
+ return;
3173
+ }
3174
+ this.handleCollaboratorDisconnect();
3175
+ };
3176
+ this.unsubFromInstanceStopped = this.channelsController.subscribeOnInstanceStop(this.id, handler.bind(this), commandId);
3177
+ }
3178
+ }
3179
+
3180
+ class ChannelsFactory {
3181
+ constructor(createUserChannelFn, createAppChannel, createPrivateChannel) {
3182
+ this.createUserChannelFn = createUserChannelFn;
3183
+ this.createAppChannel = createAppChannel;
3184
+ this.createPrivateChannel = createPrivateChannel;
3185
+ }
3186
+ buildModel(data) {
3187
+ const { type } = data;
3188
+ const lowerType = type === null || type === void 0 ? void 0 : type.toLowerCase();
3189
+ if (lowerType === ChannelTypes.User) {
3190
+ return this.createUserChannelFn(data.displayMetadata.glueChannel);
3191
+ }
3192
+ if (lowerType === ChannelTypes.App) {
3193
+ return this.createAppChannel(data.id);
3194
+ }
3195
+ if (lowerType === ChannelTypes.Private) {
3196
+ return this.createPrivateChannel(data.logger, data.id, data.isCreator);
3197
+ }
3198
+ throw new Error("Pass one of the supported channel types: user, app, private");
2990
3199
  }
2991
3200
  }
2992
3201
 
2993
3202
  class GlueEventsController {
2994
- constructor(glueController, channelsCallbackRegistry) {
3203
+ constructor(glueController, channelsStateStore, appsStateStore) {
2995
3204
  this.glueController = glueController;
2996
- this.channelsCallbackRegistry = channelsCallbackRegistry;
3205
+ this.channelsStateStore = channelsStateStore;
3206
+ this.appsStateStore = appsStateStore;
3207
+ this.actionDictionary = {
3208
+ joinPrivateChannel: this.handleJoin.bind(this),
3209
+ publishOnPrivateChannel: this.handlePublish.bind(this),
3210
+ addedContextListenerOnPrivateChannel: this.handleContextListenerAdded.bind(this),
3211
+ removedContextListenerOnPrivateChannel: this.handleContextListenerRemoved.bind(this),
3212
+ disconnectedFromPrivateChannel: this.handleDisconnect.bind(this),
3213
+ startupContextOpened: this.handleStartupContextOpened.bind(this)
3214
+ };
2997
3215
  }
2998
- initialize() {
3216
+ initializeCollaborateMethod() {
2999
3217
  return __awaiter(this, void 0, void 0, function* () {
3000
- const isMethodRegisteredByThisApp = this.isSysMethodRegisteredByCurrentApp();
3001
- if (isMethodRegisteredByThisApp) {
3218
+ const methodRegisteredByMe = this.checkSystemMethodRegistered();
3219
+ if (methodRegisteredByMe) {
3002
3220
  return;
3003
3221
  }
3004
- yield this.glueController.registerMethod(Glue42FDC3SystemMethod, this.handleSystemMethodInvocation.bind(this));
3222
+ yield this.glueController.registerMethod(ioConnectFDC3SystemMethod, this.handleReceivedAction.bind(this));
3005
3223
  });
3006
3224
  }
3007
- isSysMethodRegisteredByCurrentApp() {
3008
- const methods = this.glueController.getInteropMethods(Glue42FDC3SystemMethod);
3009
- const myId = this.glueController.getMyInteropInstanceId();
3225
+ checkSystemMethodRegistered() {
3226
+ const methods = this.glueController.getInteropMethods(ioConnectFDC3SystemMethod);
3227
+ const myId = this.glueController.getMyInteropInstance().instance;
3010
3228
  const methodsByThisInstance = methods.filter(method => {
3011
3229
  return method.getServers().find(server => server.instance === myId)
3012
3230
  ? method
@@ -3014,29 +3232,111 @@
3014
3232
  });
3015
3233
  return !!methodsByThisInstance.length;
3016
3234
  }
3017
- handleSystemMethodInvocation(argumentObj) {
3018
- const argsDecodeResult = SystemMethodInvocationArgumentDecoder.run(argumentObj);
3019
- if (!argsDecodeResult.ok) {
3020
- throw new Error(`Interop Method ${Glue42FDC3SystemMethod} invoked with invalid argument object - ${argsDecodeResult.error}.\n Expected ${JSON.stringify({ action: string, payload: { channelId: string, clientId: string } })}`);
3235
+ handleReceivedAction(eventArgs, instance) {
3236
+ return __awaiter(this, void 0, void 0, function* () {
3237
+ const argsDecodeResult = SystemMethodInvocationArgumentDecoder.run(eventArgs);
3238
+ if (!argsDecodeResult.ok) {
3239
+ throw new Error(`Interop Method ${ioConnectFDC3SystemMethod} invoked with invalid argument object - ${argsDecodeResult.error}`);
3240
+ }
3241
+ const commandId = generateCommandId();
3242
+ this.logger.log(`${commandId} - received system method from instance with id ${instance.instance} for action ${eventArgs.action} with arguments: ${JSON.stringify(eventArgs)}`);
3243
+ const operation = this.actionDictionary[eventArgs.action];
3244
+ if (!operation) {
3245
+ const errorMsg = `Unsupported private channel action: ${eventArgs.action}`;
3246
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3247
+ throw new Error(errorMsg);
3248
+ }
3249
+ yield operation(eventArgs, instance, commandId);
3250
+ });
3251
+ }
3252
+ get logger() {
3253
+ if (!this._logger) {
3254
+ this._logger = this.glueController.initSubLogger("fdc3.private.channels.controller");
3255
+ }
3256
+ return this._logger;
3257
+ }
3258
+ validateAndRetrieveChannel({ action, correlationId }, instance, commandId) {
3259
+ const privateChannel = this.channelsStateStore.getPrivateChannelById(correlationId);
3260
+ if (!privateChannel) {
3261
+ const errorMsg = `There's no private channel with id ${correlationId}`;
3262
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3263
+ throw new Error(errorMsg);
3021
3264
  }
3022
- const { action, payload } = argsDecodeResult.result;
3023
- if (action === PrivateChannelEventMethods.OnDisconnect) {
3024
- return this.handleOnDisconnect(payload);
3265
+ const channelCollaborator = privateChannel.getCollaborator();
3266
+ if (action === "joinPrivateChannel") {
3267
+ return privateChannel;
3025
3268
  }
3026
- if (action === PrivateChannelEventMethods.OnAddContextListener || action === PrivateChannelEventMethods.OnUnsubscribe) {
3027
- return this.channelsCallbackRegistry.invoke(action, payload);
3269
+ if (channelCollaborator && channelCollaborator.instanceId === instance.instance) {
3270
+ this.logger.log(`[${commandId}] - request sent from correct collaborator with id ${instance.instance}. Returning channel`);
3271
+ return privateChannel;
3028
3272
  }
3273
+ const errorMsg = `Cannot proceed with action ${action} - ${channelCollaborator
3274
+ ? `private channel ${correlationId} established communication with collaborator with id ${channelCollaborator}`
3275
+ : `no collaborator joined private channel with id ${correlationId}`}`;
3276
+ this.logger.error(errorMsg);
3277
+ throw new Error(errorMsg);
3029
3278
  }
3030
- handleOnDisconnect(payload) {
3031
- if (payload.replayContextTypes) {
3032
- this.invokeOnUnsubscribeHandlerMultipleTimes(payload);
3279
+ handleJoin(eventArgs, instance, commandId) {
3280
+ return __awaiter(this, void 0, void 0, function* () {
3281
+ const collaborator = { appId: instance.application || instance.applicationName, instanceId: instance.instance };
3282
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3283
+ yield privateChannel.handleCollaboratorJoin(collaborator, commandId);
3284
+ this.logger.log(`[${commandId}] - collaborator ${JSON.stringify(collaborator)} set for private channel with id ${eventArgs.correlationId}`);
3285
+ });
3286
+ }
3287
+ handlePublish(eventArgs, instance, commandId) {
3288
+ var _a, _b;
3289
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} action, adding context with type ${(_a = eventArgs.collaborationObject) === null || _a === void 0 ? void 0 : _a.contextType} to the private channel broadcasted contexts`);
3290
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3291
+ const metadata = {
3292
+ source: {
3293
+ appId: instance.application || instance.applicationName || "",
3294
+ instanceId: instance.instance
3295
+ }
3296
+ };
3297
+ privateChannel.handleCollaboratorBroadcast((_b = eventArgs.collaborationObject) === null || _b === void 0 ? void 0 : _b.payload, metadata, commandId);
3298
+ }
3299
+ handleContextListenerAdded(eventArgs, instance, commandId) {
3300
+ var _a;
3301
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onAddContextListener' callbacks`);
3302
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3303
+ privateChannel.handleCollaboratorAddContextListener(((_a = eventArgs.collaborationObject) === null || _a === void 0 ? void 0 : _a.contextType) || null, commandId);
3304
+ }
3305
+ handleContextListenerRemoved(eventArgs, instance, commandId) {
3306
+ var _a;
3307
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onUnsubscribe' callbacks`);
3308
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3309
+ privateChannel.handleCollaboratorRemovedListener(((_a = eventArgs.collaborationObject) === null || _a === void 0 ? void 0 : _a.contextType) || null, commandId);
3310
+ }
3311
+ handleDisconnect(eventArgs, instance, commandId) {
3312
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onDisconnect' callbacks`);
3313
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3314
+ privateChannel.handleCollaboratorDisconnect();
3315
+ }
3316
+ handleStartupContextOpened(eventArgs, instance, commandId) {
3317
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} with correlationId: ${eventArgs.correlationId} from instance with id ${instance.instance}`);
3318
+ const wrappedPromise = this.appsStateStore.getOpenAppPromise(eventArgs.correlationId);
3319
+ if (!wrappedPromise) {
3320
+ this.logger.log(`[${commandId}] - there's no open app promise related to guid ${eventArgs.correlationId}`);
3321
+ return;
3033
3322
  }
3034
- this.channelsCallbackRegistry.invoke(PrivateChannelEventMethods.OnDisconnect, payload);
3323
+ this.logger.log(`[${commandId}] - resolving open app promise related to guid ${eventArgs.correlationId} from instance with id ${instance.instance}`);
3324
+ wrappedPromise.resolve();
3035
3325
  }
3036
- invokeOnUnsubscribeHandlerMultipleTimes(payload) {
3037
- payload.replayContextTypes.forEach(contextType => {
3038
- this.channelsCallbackRegistry.invoke(PrivateChannelEventMethods.OnUnsubscribe, { channelId: payload.channelId, clientId: payload.clientId, contextType });
3039
- });
3326
+ }
3327
+
3328
+ class ApplicationsStateStore {
3329
+ constructor() {
3330
+ this.openAppPromises = {};
3331
+ }
3332
+ addOpenAppPromise(guid, promise) {
3333
+ this.openAppPromises[guid] = promise;
3334
+ }
3335
+ getOpenAppPromise(guid) {
3336
+ return this.openAppPromises[guid];
3337
+ }
3338
+ removeOpenAppPromise(guid) {
3339
+ delete this.openAppPromises[guid];
3040
3340
  }
3041
3341
  }
3042
3342
 
@@ -3046,7 +3346,7 @@
3046
3346
  }
3047
3347
  get eventReceiver() {
3048
3348
  if (!this._eventReceiver) {
3049
- this._eventReceiver = new EventReceiver(this.glueController, this.eventDispatcher, this.eventsController);
3349
+ this._eventReceiver = new EventReceiver(this.glueController, this.eventDispatcher);
3050
3350
  }
3051
3351
  return this._eventReceiver;
3052
3352
  }
@@ -3080,8 +3380,8 @@
3080
3380
  createAppChannel(id) {
3081
3381
  return new AppChannel(this.channelsController, id).toApi();
3082
3382
  }
3083
- createPrivateChannel(channelId) {
3084
- return new PrivateChannel(this.channelsController, channelId).toApi();
3383
+ createPrivateChannel(logger, channelId, isCreator) {
3384
+ return new PrivateChannel(this.channelsController, logger, channelId, isCreator);
3085
3385
  }
3086
3386
  get desktopAgent() {
3087
3387
  if (!this._desktopAgent) {
@@ -3097,19 +3397,19 @@
3097
3397
  }
3098
3398
  get intentsController() {
3099
3399
  if (!this._intentsController) {
3100
- this._intentsController = new IntentsController(this.glueController, this.channelsController, this.channelsFactory);
3400
+ this._intentsController = new IntentsController(this.glueController, this.channelsController, this.channelsFactory, this.eventsController);
3101
3401
  }
3102
3402
  return this._intentsController;
3103
3403
  }
3104
3404
  get applicationController() {
3105
3405
  if (!this._applicationController) {
3106
- this._applicationController = new ApplicationsController(this.glueController);
3406
+ this._applicationController = new ApplicationsController(this.glueController, this.applicationsStateStore, this.eventsController);
3107
3407
  }
3108
3408
  return this._applicationController;
3109
3409
  }
3110
3410
  get channelsController() {
3111
3411
  if (!this._channelsController) {
3112
- this._channelsController = new ChannelsController(this.glueController, this.channelsStateStore, this.channelsParser, this.channelsFactory, this.channelsCallbackRegistry);
3412
+ this._channelsController = new ChannelsController(this.glueController, this.channelsStateStore, this.channelsParser, this.channelsFactory, this.eventsController);
3113
3413
  }
3114
3414
  return this._channelsController;
3115
3415
  }
@@ -3119,18 +3419,18 @@
3119
3419
  }
3120
3420
  return this._channelsStateStore;
3121
3421
  }
3122
- get channelsCallbackRegistry() {
3123
- if (!this._channelsCallbackRegistry) {
3124
- this._channelsCallbackRegistry = new ChannelsCallbackRegistry();
3125
- }
3126
- return this._channelsCallbackRegistry;
3127
- }
3128
3422
  get eventsController() {
3129
3423
  if (!this._eventsController) {
3130
- this._eventsController = new GlueEventsController(this.glueController, this.channelsCallbackRegistry);
3424
+ this._eventsController = new GlueEventsController(this.glueController, this.channelsStateStore, this.applicationsStateStore);
3131
3425
  }
3132
3426
  return this._eventsController;
3133
3427
  }
3428
+ get applicationsStateStore() {
3429
+ if (!this._applicationsStateStore) {
3430
+ this._applicationsStateStore = new ApplicationsStateStore();
3431
+ }
3432
+ return this._applicationsStateStore;
3433
+ }
3134
3434
  }
3135
3435
 
3136
3436
  const fdc3Factory = () => {