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