@interopio/fdc3-web-bridge 1.5.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,13 +3,13 @@
3
3
  factory();
4
4
  })((function () { 'use strict';
5
5
 
6
- /* @ts-self-types="./index.d.ts" */
7
6
  let urlAlphabet =
8
7
  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
8
+
9
9
  let nanoid = (size = 21) => {
10
10
  let id = '';
11
11
  let i = size | 0;
12
- while (i--) {
12
+ while (i-- > 0) {
13
13
  id += urlAlphabet[(Math.random() * 64) | 0];
14
14
  }
15
15
  return id
@@ -760,7 +760,7 @@
760
760
  /** See `Decoder.string` */
761
761
  var string$1 = Decoder$1.string;
762
762
  /** See `Decoder.number` */
763
- Decoder$1.number;
763
+ var number$1 = Decoder$1.number;
764
764
  /** See `Decoder.boolean` */
765
765
  var boolean$1 = Decoder$1.boolean;
766
766
  /** See `Decoder.anyJson` */
@@ -1550,7 +1550,7 @@
1550
1550
  /** See `Decoder.anyJson` */
1551
1551
  var anyJson = Decoder.anyJson;
1552
1552
  /** See `Decoder.unknownJson` */
1553
- Decoder.unknownJson;
1553
+ var unknownJson = Decoder.unknownJson;
1554
1554
  /** See `Decoder.constant` */
1555
1555
  var constant = Decoder.constant;
1556
1556
  /** See `Decoder.object` */
@@ -1568,13 +1568,13 @@
1568
1568
  /** See `Decoder.union` */
1569
1569
  Decoder.union;
1570
1570
  /** See `Decoder.intersection` */
1571
- Decoder.intersection;
1571
+ var intersection = Decoder.intersection;
1572
1572
  /** See `Decoder.withDefault` */
1573
1573
  Decoder.withDefault;
1574
1574
  /** See `Decoder.valueAt` */
1575
1575
  Decoder.valueAt;
1576
1576
  /** See `Decoder.succeed` */
1577
- Decoder.succeed;
1577
+ var succeed = Decoder.succeed;
1578
1578
  /** See `Decoder.fail` */
1579
1579
  var fail = Decoder.fail;
1580
1580
  /** See `Decoder.lazy` */
@@ -1582,9 +1582,12 @@
1582
1582
 
1583
1583
  const nonEmptyStringDecoder$4 = string().where((s) => s.length > 0, "Expected a non-empty string");
1584
1584
  const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number");
1585
+ const positiveNumberDecoder = number().where((num) => num > 0, "Expected a positive number");
1586
+ const nullable$2 = (decoder) => unknownJson().andThen((value) => value === null ? succeed(null) : decoder);
1585
1587
  const regexDecoder = anyJson().andThen((value) => {
1586
1588
  return value instanceof RegExp ? anyJson() : fail(`expected a regex, got a ${typeof value}`);
1587
1589
  });
1590
+ const looseObjectDecoder = (fieldDecoders) => intersection(object(), object(fieldDecoders));
1588
1591
  const urlDecoder = nonEmptyStringDecoder$4.andThen((url) => {
1589
1592
  try {
1590
1593
  const { protocol } = new URL(url);
@@ -1926,8 +1929,11 @@
1926
1929
  common: {
1927
1930
  nonEmptyStringDecoder: nonEmptyStringDecoder$4,
1928
1931
  nonNegativeNumberDecoder,
1932
+ positiveNumberDecoder,
1933
+ nullable: nullable$2,
1929
1934
  regexDecoder,
1930
- urlDecoder
1935
+ urlDecoder,
1936
+ looseObjectDecoder
1931
1937
  },
1932
1938
  fdc3: {
1933
1939
  allDefinitionsDecoder,
@@ -1977,8 +1983,8 @@
1977
1983
  ioc.errors;
1978
1984
 
1979
1985
  const { nonEmptyStringDecoder: nonEmptyStringDecoder$3 } = decoders.common;
1980
- const requestMessageTypeDecoder = oneOf$1(constant$1("addContextListenerRequest"), constant$1("addEventListenerRequest"), constant$1("addIntentListenerRequest"), constant$1("broadcastRequest"), constant$1("contextListenerUnsubscribeRequest"), constant$1("createPrivateChannelRequest"), constant$1("eventListenerUnsubscribeRequest"), constant$1("findInstancesRequest"), constant$1("findIntentRequest"), constant$1("findIntentsByContextRequest"), constant$1("getAppMetadataRequest"), constant$1("getCurrentChannelRequest"), constant$1("getCurrentContextRequest"), constant$1("getInfoRequest"), constant$1("getOrCreateChannelRequest"), constant$1("getUserChannelsRequest"), constant$1("heartbeatAcknowledgementRequest"), constant$1("intentListenerUnsubscribeRequest"), constant$1("intentResultRequest"), constant$1("joinUserChannelRequest"), constant$1("leaveCurrentChannelRequest"), constant$1("openRequest"), constant$1("privateChannelAddEventListenerRequest"), constant$1("privateChannelDisconnectRequest"), constant$1("privateChannelUnsubscribeEventListenerRequest"), constant$1("raiseIntentForContextRequest"), constant$1("raiseIntentRequest"));
1981
- const responseMessageTypeDecoder = oneOf$1(constant$1("addContextListenerResponse"), constant$1("addEventListenerResponse"), constant$1("addIntentListenerResponse"), constant$1("broadcastResponse"), constant$1("contextListenerUnsubscribeResponse"), constant$1("createPrivateChannelResponse"), constant$1("eventListenerUnsubscribeResponse"), constant$1("findInstancesResponse"), constant$1("findIntentResponse"), constant$1("findIntentsByContextResponse"), constant$1("getAppMetadataResponse"), constant$1("getCurrentChannelResponse"), constant$1("getCurrentContextResponse"), constant$1("getInfoResponse"), constant$1("getOrCreateChannelResponse"), constant$1("getUserChannelsResponse"), constant$1("intentListenerUnsubscribeResponse"), constant$1("intentResultResponse"), constant$1("joinUserChannelResponse"), constant$1("leaveCurrentChannelResponse"), constant$1("openResponse"), constant$1("privateChannelAddEventListenerResponse"), constant$1("privateChannelDisconnectResponse"), constant$1("privateChannelUnsubscribeEventListenerResponse"), constant$1("raiseIntentForContextResponse"), constant$1("raiseIntentResponse"), constant$1("raiseIntentResultResponse"));
1986
+ const requestMessageTypeDecoder = oneOf$1(constant$1("addContextListenerRequest"), constant$1("addEventListenerRequest"), constant$1("addIntentListenerRequest"), constant$1("broadcastRequest"), constant$1("clearContextRequest"), constant$1("contextListenerUnsubscribeRequest"), constant$1("createPrivateChannelRequest"), constant$1("eventListenerUnsubscribeRequest"), constant$1("findInstancesRequest"), constant$1("findIntentRequest"), constant$1("findIntentsByContextRequest"), constant$1("getAppMetadataRequest"), constant$1("getCurrentChannelRequest"), constant$1("getCurrentContextRequest"), constant$1("getInfoRequest"), constant$1("getOrCreateChannelRequest"), constant$1("getUserChannelsRequest"), constant$1("heartbeatAcknowledgementRequest"), constant$1("intentListenerUnsubscribeRequest"), constant$1("intentResultRequest"), constant$1("joinUserChannelRequest"), constant$1("leaveCurrentChannelRequest"), constant$1("openRequest"), constant$1("privateChannelAddEventListenerRequest"), constant$1("privateChannelDisconnectRequest"), constant$1("privateChannelUnsubscribeEventListenerRequest"), constant$1("raiseIntentForContextRequest"), constant$1("raiseIntentRequest"), constant$1("closeRequest"));
1987
+ const responseMessageTypeDecoder = oneOf$1(constant$1("addContextListenerResponse"), constant$1("addEventListenerResponse"), constant$1("addIntentListenerResponse"), constant$1("broadcastResponse"), constant$1("clearContextResponse"), constant$1("contextListenerUnsubscribeResponse"), constant$1("createPrivateChannelResponse"), constant$1("eventListenerUnsubscribeResponse"), constant$1("findInstancesResponse"), constant$1("findIntentResponse"), constant$1("findIntentsByContextResponse"), constant$1("getAppMetadataResponse"), constant$1("getCurrentChannelResponse"), constant$1("getCurrentContextResponse"), constant$1("getInfoResponse"), constant$1("getOrCreateChannelResponse"), constant$1("getUserChannelsResponse"), constant$1("intentListenerUnsubscribeResponse"), constant$1("intentResultResponse"), constant$1("joinUserChannelResponse"), constant$1("leaveCurrentChannelResponse"), constant$1("openResponse"), constant$1("privateChannelAddEventListenerResponse"), constant$1("privateChannelDisconnectResponse"), constant$1("privateChannelUnsubscribeEventListenerResponse"), constant$1("raiseIntentForContextResponse"), constant$1("raiseIntentResponse"), constant$1("raiseIntentResultResponse"), constant$1("closeResponse"));
1982
1988
  const webConnectionProtocolMessageTypeDecoder = oneOf$1(constant$1("WCP1Hello"), constant$1("WCP2LoadUrl"), constant$1("WCP3Handshake"), constant$1("WCP4ValidateAppIdentity"), constant$1("WCP5ValidateAppIdentityFailedResponse"), constant$1("WCP5ValidateAppIdentityResponse"), constant$1("WCP6Goodbye"));
1983
1989
  const appIdentifierDecoder = object$1({
1984
1990
  appId: nonEmptyStringDecoder$3,
@@ -1987,18 +1993,18 @@
1987
1993
  });
1988
1994
  const appRequestMetaDecoder = object$1({
1989
1995
  requestUuid: nonEmptyStringDecoder$3,
1990
- timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
1996
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
1991
1997
  source: optional$1(appIdentifierDecoder)
1992
1998
  });
1993
1999
  const responseMetaDecoder = object$1({
1994
2000
  requestUuid: nonEmptyStringDecoder$3,
1995
2001
  responseUuid: nonEmptyStringDecoder$3,
1996
2002
  source: optional$1(appIdentifierDecoder),
1997
- timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2003
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
1998
2004
  });
1999
2005
  const connectionStepMetaDecoder = object$1({
2000
2006
  connectionAttemptUuid: nonEmptyStringDecoder$3,
2001
- timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2007
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2002
2008
  });
2003
2009
  object$1({
2004
2010
  type: webConnectionProtocolMessageTypeDecoder,
@@ -2010,8 +2016,8 @@
2010
2016
  name: optional$1(nonEmptyStringDecoder$3),
2011
2017
  id: optional$1(anyJson$1()),
2012
2018
  });
2013
- const responsePayloadErrorDecoder = oneOf$1(constant$1("AccessDenied"), constant$1("CreationFailed"), constant$1("MalformedContext"), constant$1("NoChannelFound"), constant$1("AppNotFound"), constant$1("AppTimeout"), constant$1("DesktopAgentNotFound"), constant$1("ErrorOnLaunch"), constant$1("ResolverUnavailable"), constant$1("IntentDeliveryFailed"), constant$1("NoAppsFound"), constant$1("ResolverTimeout"), constant$1("TargetAppUnavailable"), constant$1("TargetInstanceUnavailable"), constant$1("UserCancelledResolution"), constant$1("IntentHandlerRejected"), constant$1("NoResultReturned"), constant$1("AgentDisconnected"), constant$1("NotConnectedToBridge"), constant$1("ResponseToBridgeTimedOut"), constant$1("MalformedMessage"));
2014
- const fluffyErrorDecoder = oneOf$1(constant$1("MalformedContext"), constant$1("DesktopAgentNotFound"), constant$1("ResolverUnavailable"), constant$1("IntentDeliveryFailed"), constant$1("NoAppsFound"), constant$1("ResolverTimeout"), constant$1("TargetAppUnavailable"), constant$1("TargetInstanceUnavailable"), constant$1("UserCancelledResolution"));
2019
+ const responsePayloadErrorDecoder = oneOf$1(constant$1("AccessDenied"), constant$1("ApiTimeout"), constant$1("InvalidArguments"), constant$1("IntentListenerConflict"), constant$1("CreationFailed"), constant$1("MalformedContext"), constant$1("NoChannelFound"), constant$1("AppNotFound"), constant$1("AppTimeout"), constant$1("DesktopAgentNotFound"), constant$1("ErrorOnLaunch"), constant$1("ResolverUnavailable"), constant$1("IntentDeliveryFailed"), constant$1("NoAppsFound"), constant$1("ResolverTimeout"), constant$1("TargetAppUnavailable"), constant$1("TargetInstanceUnavailable"), constant$1("UserCancelledResolution"), constant$1("IntentHandlerRejected"), constant$1("NoResultReturned"), constant$1("AgentDisconnected"), constant$1("NotConnectedToBridge"), constant$1("ResponseToBridgeTimedOut"), constant$1("MalformedMessage"));
2020
+ const fluffyErrorDecoder = oneOf$1(constant$1("MalformedContext"), constant$1("ApiTimeout"), constant$1("InvalidArguments"), constant$1("DesktopAgentNotFound"), constant$1("ResolverUnavailable"), constant$1("IntentDeliveryFailed"), constant$1("NoAppsFound"), constant$1("ResolverTimeout"), constant$1("TargetAppUnavailable"), constant$1("TargetInstanceUnavailable"), constant$1("UserCancelledResolution"), constant$1("IntentListenerConflict"));
2015
2021
  const wcp1HelloPayloadDecoder = object$1({
2016
2022
  actualUrl: nonEmptyStringDecoder$3,
2017
2023
  channelSelector: optional$1(boolean$1()),
@@ -2021,7 +2027,7 @@
2021
2027
  });
2022
2028
  const wcp1HelloMetaDecoder = object$1({
2023
2029
  connectionAttemptUuid: nonEmptyStringDecoder$3,
2024
- timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2030
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2025
2031
  });
2026
2032
  const wcp1HelloDecoder = object$1({
2027
2033
  type: constant$1("WCP1Hello"),
@@ -2091,7 +2097,6 @@
2091
2097
  });
2092
2098
  const optionalFeaturesDecoder = object$1({
2093
2099
  DesktopAgentBridging: boolean$1(),
2094
- OriginatingAppMetadata: boolean$1(),
2095
2100
  UserChannelMembershipAPIs: boolean$1()
2096
2101
  });
2097
2102
  const implementationMetadataDecoder = object$1({
@@ -2112,17 +2117,43 @@
2112
2117
  meta: wcp1HelloMetaDecoder,
2113
2118
  payload: wcp5ValidateAppIdentitySuccessResponsePayloadDecoder
2114
2119
  });
2120
+ const detachedSignatureDecoder = object$1({
2121
+ protected: string$1(),
2122
+ signature: string$1()
2123
+ });
2124
+ const antiReplayClaimsDecoder = object$1({
2125
+ iat: number$1(),
2126
+ exp: number$1(),
2127
+ jti: string$1()
2128
+ });
2129
+ const appProvidableContextMetadataDecoder = object$1({
2130
+ traceId: optional$1(string$1()),
2131
+ signature: optional$1(detachedSignatureDecoder),
2132
+ antiReplay: optional$1(antiReplayClaimsDecoder),
2133
+ custom: optional$1(object$1())
2134
+ }).where((metadata) => !metadata.signature || !!metadata.antiReplay, "Expected antiReplay claims when signature is provided");
2135
+ const optionalAppProvidableContextMetadataDecoder = optional$1(appProvidableContextMetadataDecoder);
2136
+ const contextMetadataDecoder = object$1({
2137
+ source: appIdentifierDecoder,
2138
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, "Expected result metadata timestamp to be a Date"),
2139
+ traceId: string$1(),
2140
+ signature: optional$1(detachedSignatureDecoder),
2141
+ antiReplay: optional$1(antiReplayClaimsDecoder),
2142
+ custom: optional$1(object$1())
2143
+ }).where((metadata) => !metadata.signature || !!metadata.antiReplay, "Expected antiReplay claims when signature is provided");
2144
+ const contextTypesStringArrayDecoder = array$1(nonEmptyStringDecoder$3).where((types) => types.length > 0, "Expected at least one context type");
2115
2145
 
2116
- const { nonEmptyStringDecoder: nonEmptyStringDecoder$2 } = decoders.common;
2146
+ const { nonEmptyStringDecoder: nonEmptyStringDecoder$2, nullable: nullable$1 } = decoders.common;
2117
2147
  const addContextListenerRequestMetaDecoder = object$1({
2118
2148
  requestUuid: nonEmptyStringDecoder$2,
2119
2149
  source: optional$1(appIdentifierDecoder),
2120
- timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2150
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2121
2151
  });
2122
2152
  const addContextListenerRequestPayloadDecoder = object$1({
2123
- channelId: optional$1(nonEmptyStringDecoder$2),
2124
- contextType: optional$1(nonEmptyStringDecoder$2)
2125
- });
2153
+ channelId: nullable$1(nonEmptyStringDecoder$2),
2154
+ contextType: nullable$1(optional$1(nonEmptyStringDecoder$2)),
2155
+ contextTypes: oneOf$1(constant$1(undefined), contextTypesStringArrayDecoder)
2156
+ }).where((payload) => (payload.contextType !== undefined) !== (payload.contextTypes !== undefined), "Expected exactly one of 'contextType' or 'contextTypes' to be present");
2126
2157
  const addContextListenerRequestDecoder = object$1({
2127
2158
  type: constant$1("addContextListenerRequest"),
2128
2159
  meta: addContextListenerRequestMetaDecoder,
@@ -2132,11 +2163,12 @@
2132
2163
  requestUuid: nonEmptyStringDecoder$2,
2133
2164
  responseUuid: nonEmptyStringDecoder$2,
2134
2165
  source: optional$1(appIdentifierDecoder),
2135
- timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2166
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2136
2167
  });
2137
- const addEventListenerTypeDecoder = oneOf$1(constant$1("USER_CHANNEL_CHANGED"));
2168
+ const addEventListenerTypeDecoder = oneOf$1(constant$1("USER_CHANNEL_CHANGED"), constant$1("CONTEXT_CLEARED"));
2138
2169
  const addEventListenerRequestPayloadDecoder = object$1({
2139
- type: optional$1(addEventListenerTypeDecoder)
2170
+ channelId: optional$1(nullable$1(nonEmptyStringDecoder$2)).map((channelId) => channelId ?? null),
2171
+ type: nullable$1(addEventListenerTypeDecoder)
2140
2172
  });
2141
2173
  const addEventListenerRequestDecoder = object$1({
2142
2174
  type: constant$1("addEventListenerRequest"),
@@ -2152,7 +2184,7 @@
2152
2184
  meta: addContextListenerResponseMetaDecoder,
2153
2185
  payload: addEventListenerResponsePayloadDecoder
2154
2186
  });
2155
- const purpleErrorDecoder = oneOf$1(constant$1("AccessDenied"), constant$1("CreationFailed"), constant$1("MalformedContext"), constant$1("NoChannelFound"));
2187
+ const purpleErrorDecoder = oneOf$1(constant$1("AccessDenied"), constant$1("CreationFailed"), constant$1("MalformedContext"), constant$1("NoChannelFound"), constant$1("ApiTimeout"), constant$1("InvalidArguments"));
2156
2188
  const addContextListenerResponsePayloadDecoder = object$1({
2157
2189
  error: optional$1(purpleErrorDecoder),
2158
2190
  listenerUUID: optional$1(nonEmptyStringDecoder$2)
@@ -2164,7 +2196,8 @@
2164
2196
  });
2165
2197
  const broadcastRequestPayloadDecoder = object$1({
2166
2198
  channelId: nonEmptyStringDecoder$2,
2167
- context: contextDecoder
2199
+ context: contextDecoder,
2200
+ metadata: optionalAppProvidableContextMetadataDecoder
2168
2201
  });
2169
2202
  const broadcastRequestDecoder = object$1({
2170
2203
  type: constant$1("broadcastRequest"),
@@ -2179,6 +2212,11 @@
2179
2212
  meta: responseMetaDecoder,
2180
2213
  payload: broadcastResponsePayloadDecoder
2181
2214
  });
2215
+ const clearContextResponseDecoder = object$1({
2216
+ type: constant$1("clearContextResponse"),
2217
+ meta: responseMetaDecoder,
2218
+ payload: broadcastResponsePayloadDecoder
2219
+ });
2182
2220
  const channelTypeDecoder = oneOf$1(constant$1("app"), constant$1("user"), constant$1("private"));
2183
2221
  const displayMetadataDecoder = object$1({
2184
2222
  color: optional$1(nonEmptyStringDecoder$2),
@@ -2193,6 +2231,15 @@
2193
2231
  const contextListenerUnsubscribeRequestPayloadDecoder = object$1({
2194
2232
  listenerUUID: nonEmptyStringDecoder$2
2195
2233
  });
2234
+ const clearContextRequestPayloadDecoder = object$1({
2235
+ channelId: nonEmptyStringDecoder$2,
2236
+ contextType: nullable$1(nonEmptyStringDecoder$2)
2237
+ });
2238
+ const clearContextRequestDecoder = object$1({
2239
+ type: constant$1("clearContextRequest"),
2240
+ meta: addContextListenerRequestMetaDecoder,
2241
+ payload: clearContextRequestPayloadDecoder
2242
+ });
2196
2243
  const contextListenerUnsubscribeRequestDecoder = object$1({
2197
2244
  type: constant$1("contextListenerUnsubscribeRequest"),
2198
2245
  meta: addContextListenerRequestMetaDecoder,
@@ -2246,7 +2293,7 @@
2246
2293
  });
2247
2294
  const getCurrentContextRequestPayloadDecoder = object$1({
2248
2295
  channelId: nonEmptyStringDecoder$2,
2249
- contextType: optional$1(nonEmptyStringDecoder$2)
2296
+ contextType: nullable$1(nonEmptyStringDecoder$2)
2250
2297
  });
2251
2298
  const getCurrentContextRequestDecoder = object$1({
2252
2299
  type: constant$1("getCurrentContextRequest"),
@@ -2255,7 +2302,8 @@
2255
2302
  });
2256
2303
  const getCurrentContextResponsePayloadDecoder = object$1({
2257
2304
  error: optional$1(purpleErrorDecoder),
2258
- context: optional$1(contextDecoder)
2305
+ context: optional$1(nullable$1(contextDecoder)),
2306
+ metadata: optional$1(nullable$1(contextMetadataDecoder))
2259
2307
  });
2260
2308
  const getCurrentContextResponseDecoder = object$1({
2261
2309
  type: constant$1("getCurrentContextResponse"),
@@ -2322,9 +2370,9 @@
2322
2370
  meta: addContextListenerResponseMetaDecoder,
2323
2371
  payload: leaveCurrentChannelResponsePayloadDecoder
2324
2372
  });
2325
- const privateChannelEventListenerTypesDecoder = oneOf$1(constant$1("addContextListener"), constant$1("unsubscribe"), constant$1("disconnect"));
2373
+ const privateChannelEventListenerTypesDecoder = oneOf$1(constant$1("addContextListener"), constant$1("unsubscribe"), constant$1("disconnect"), constant$1("contextCleared"));
2326
2374
  const privateChannelAddEventListenerRequestPayloadDecoder = object$1({
2327
- listenerType: optional$1(privateChannelEventListenerTypesDecoder),
2375
+ listenerType: nullable$1(privateChannelEventListenerTypesDecoder),
2328
2376
  privateChannelId: nonEmptyStringDecoder$2
2329
2377
  });
2330
2378
  const privateChannelAddEventListenerRequestDecoder = object$1({
@@ -2369,7 +2417,7 @@
2369
2417
  });
2370
2418
  const broadcastEventMetaDecoder = object$1({
2371
2419
  eventUuid: nonEmptyStringDecoder$2,
2372
- timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2420
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2373
2421
  });
2374
2422
 
2375
2423
  const { nonEmptyStringDecoder: nonEmptyStringDecoder$1 } = decoders.common;
@@ -2396,7 +2444,8 @@
2396
2444
  });
2397
2445
  const openRequestPayloadDecoder = object$1({
2398
2446
  app: appIdentifierDecoder,
2399
- context: optional$1(contextDecoder)
2447
+ context: optional$1(contextDecoder),
2448
+ metadata: optionalAppProvidableContextMetadataDecoder
2400
2449
  });
2401
2450
  const openRequestDecoder = object$1({
2402
2451
  type: constant$1("openRequest"),
@@ -2455,17 +2504,171 @@
2455
2504
  meta: broadcastEventMetaDecoder,
2456
2505
  payload: heartbeatEventPayloadDecoder
2457
2506
  });
2507
+ const closeRequestDecoder = object$1({
2508
+ type: constant$1("closeRequest"),
2509
+ meta: addContextListenerRequestMetaDecoder,
2510
+ payload: anyJson$1()
2511
+ });
2512
+ const closeResponsePayloadError = constant$1('ApiTimeout');
2513
+ const closeResponsePayloadDecoder = object$1({
2514
+ error: optional$1(closeResponsePayloadError)
2515
+ });
2516
+ const closeResponseDecoder = object$1({
2517
+ type: constant$1("closeResponse"),
2518
+ meta: addContextListenerResponseMetaDecoder,
2519
+ payload: closeResponsePayloadDecoder
2520
+ });
2521
+
2522
+ var WCPMessageTypes;
2523
+ (function (WCPMessageTypes) {
2524
+ WCPMessageTypes["WCP1Hello"] = "WCP1Hello";
2525
+ WCPMessageTypes["WCP2LoadUrl"] = "WCP2LoadUrl";
2526
+ WCPMessageTypes["WCP3Handshake"] = "WCP3Handshake";
2527
+ WCPMessageTypes["WCP4ValidateAppIdentity"] = "WCP4ValidateAppIdentity";
2528
+ WCPMessageTypes["WCP5ValidateAppIdentityFailedResponse"] = "WCP5ValidateAppIdentityFailedResponse";
2529
+ WCPMessageTypes["WCP5ValidateAppIdentityResponse"] = "WCP5ValidateAppIdentityResponse";
2530
+ WCPMessageTypes["WCP6Goodbye"] = "WCP6Goodbye";
2531
+ })(WCPMessageTypes || (WCPMessageTypes = {}));
2532
+ const FDC3_READY_TIMEOUT = 120 * 1000;
2533
+ const channelTypes = ["user", "app", "private"];
2534
+ const defaultChannelsProps = ["id", "type", "broadcast", "addContextListener", "getCurrentContext"];
2535
+
2536
+ const rejectWithErrorObj = (reject, error) => {
2537
+ if (error instanceof Error) {
2538
+ reject(error.message);
2539
+ return;
2540
+ }
2541
+ if (typeof error === "string") {
2542
+ reject(new Error(error));
2543
+ return;
2544
+ }
2545
+ reject(new Error(JSON.stringify(error)));
2546
+ };
2547
+ const wrapPromise = () => {
2548
+ let wrapperResolve;
2549
+ let wrapperReject;
2550
+ const promise = new Promise((resolve, reject) => {
2551
+ wrapperResolve = resolve;
2552
+ wrapperReject = reject;
2553
+ });
2554
+ return { promise, resolve: wrapperResolve, reject: wrapperReject };
2555
+ };
2556
+ const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => {
2557
+ return new Promise((resolve, reject) => {
2558
+ const timeout = setTimeout(() => {
2559
+ const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`;
2560
+ reject(new Error(message));
2561
+ }, timeoutMilliseconds);
2562
+ promise()
2563
+ .then((result) => {
2564
+ clearTimeout(timeout);
2565
+ resolve(result);
2566
+ })
2567
+ .catch((error) => {
2568
+ clearTimeout(timeout);
2569
+ rejectWithErrorObj(reject, error);
2570
+ });
2571
+ });
2572
+ };
2573
+ const compareOrigins = (url1, url2) => {
2574
+ try {
2575
+ const parsedUrl1 = new URL(url1);
2576
+ const parsedUrl2 = new URL(url2);
2577
+ return parsedUrl1.origin === parsedUrl2.origin;
2578
+ }
2579
+ catch {
2580
+ return false;
2581
+ }
2582
+ };
2583
+ const removeTrailingSlash = (pathname) => {
2584
+ return pathname.endsWith("/")
2585
+ ? pathname.slice(0, -1)
2586
+ : pathname;
2587
+ };
2588
+ const isRecordUrlMatchToIdentityUrl = (recordUrl, identityUrl) => {
2589
+ let parsedRecordUrl;
2590
+ let parsedIdentityUrl;
2591
+ try {
2592
+ parsedRecordUrl = new URL(recordUrl);
2593
+ parsedIdentityUrl = new URL(identityUrl);
2594
+ }
2595
+ catch {
2596
+ return false;
2597
+ }
2598
+ if (parsedRecordUrl.origin !== parsedIdentityUrl.origin) {
2599
+ return false;
2600
+ }
2601
+ const recordPath = removeTrailingSlash(parsedRecordUrl.pathname);
2602
+ const identityPath = removeTrailingSlash(parsedIdentityUrl.pathname);
2603
+ if (recordPath !== identityPath) {
2604
+ return false;
2605
+ }
2606
+ for (const [key, value] of parsedRecordUrl.searchParams) {
2607
+ if (parsedIdentityUrl.searchParams.get(key) !== value) {
2608
+ return false;
2609
+ }
2610
+ }
2611
+ if (parsedRecordUrl.hash && parsedRecordUrl.hash !== parsedIdentityUrl.hash) {
2612
+ return false;
2613
+ }
2614
+ return true;
2615
+ };
2616
+ const checkIfFDC3Channel = (object) => {
2617
+ if (!object || typeof object !== "object" || Array.isArray(object)) {
2618
+ return false;
2619
+ }
2620
+ if (!channelTypes.includes(object?.type)) {
2621
+ return false;
2622
+ }
2623
+ return defaultChannelsProps.every((prop) => Object.keys(object).includes(prop));
2624
+ };
2625
+ const checkIfFDC3Context = (object) => {
2626
+ if (!object || typeof object !== "object" || Array.isArray(object)) {
2627
+ return false;
2628
+ }
2629
+ return "type" in object && typeof object.type === "string";
2630
+ };
2631
+ const checkIfFDC3ContextWithMetadata = (object) => {
2632
+ if (!object || typeof object !== "object") {
2633
+ return false;
2634
+ }
2635
+ const hasContextAndMetadata = "context" in object && "metadata" in object;
2636
+ if (!hasContextAndMetadata) {
2637
+ return false;
2638
+ }
2639
+ const isValidContext = checkIfFDC3Context(object.context);
2640
+ if (!isValidContext) {
2641
+ return false;
2642
+ }
2643
+ const decodedMetadata = contextMetadataDecoder.run(object.metadata);
2644
+ return decodedMetadata.ok;
2645
+ };
2646
+ const buildEnrichedMetadata = (metadata, myAppMetadata) => {
2647
+ return {
2648
+ ...(metadata ?? {}),
2649
+ custom: {
2650
+ ...(metadata?.custom ?? {}),
2651
+ ___source___: {
2652
+ appId: myAppMetadata.appId,
2653
+ instanceId: myAppMetadata.instanceId,
2654
+ }
2655
+ }
2656
+ };
2657
+ };
2458
2658
 
2459
2659
  class ApplicationsController {
2660
+ myAppMetadata;
2460
2661
  logger;
2461
2662
  operations = {
2462
2663
  findInstancesRequest: { requestType: "findInstancesRequest", requestDecoder: findInstancesRequestDecoder, responseType: "findInstancesResponse", responseDecoder: findInstancesResponseDecoder, execute: this.handleFindInstancesRequest.bind(this) },
2463
2664
  getAppMetadataRequest: { requestType: "getAppMetadataRequest", requestDecoder: getAppMetadataRequestDecoder, responseType: "getAppMetadataResponse", responseDecoder: getAppMetadataResponseDecoder, execute: this.handleGetAppMetadataRequest.bind(this) },
2464
2665
  getInfoRequest: { requestType: "getInfoRequest", requestDecoder: getInfoRequestDecoder, responseType: "getInfoResponse", responseDecoder: getInfoResponseDecoder, execute: this.handleGetInfoRequest.bind(this) },
2465
2666
  openRequest: { requestType: "openRequest", requestDecoder: openRequestDecoder, responseType: "openResponse", responseDecoder: openResponseDecoder, execute: this.handleOpenRequest.bind(this) },
2466
- heartbeatAcknowledgementRequest: { requestType: "heartbeatAcknowledgementRequest", requestDecoder: heartbeatAcknowledgementRequestDecoder, responseType: "heartbeatEvent", responseDecoder: heartbeatEventDecoder, execute: this.handleHeartbeatAcknowledgementRequest.bind(this) }
2667
+ heartbeatAcknowledgementRequest: { requestType: "heartbeatAcknowledgementRequest", requestDecoder: heartbeatAcknowledgementRequestDecoder, responseType: "heartbeatEvent", responseDecoder: heartbeatEventDecoder, execute: this.handleHeartbeatAcknowledgementRequest.bind(this) },
2668
+ closeRequest: { requestType: "closeRequest", requestDecoder: closeRequestDecoder, responseType: "closeResponse", responseDecoder: closeResponseDecoder, execute: this.handleCloseRequest.bind(this) },
2467
2669
  };
2468
- constructor(logger) {
2670
+ constructor(myAppMetadata, logger) {
2671
+ this.myAppMetadata = myAppMetadata;
2469
2672
  this.logger = logger;
2470
2673
  }
2471
2674
  async handleControl(request) {
@@ -2500,24 +2703,51 @@
2500
2703
  this.logger?.info(`Returning response: ${JSON.stringify(response)}`);
2501
2704
  return response;
2502
2705
  }
2706
+ async handlePostResponse(request) {
2707
+ const operation = this.operations[request.type];
2708
+ await operation.postResponse?.(request);
2709
+ }
2503
2710
  async handleFindInstancesRequest({ payload }) {
2504
- const appIdentifiers = await window.fdc3?.findInstances(payload.app);
2711
+ if (!window.fdc3) {
2712
+ return { error: "ApiTimeout" };
2713
+ }
2714
+ const appIdentifiers = await window.fdc3.findInstances(payload.app);
2505
2715
  return { appIdentifiers };
2506
2716
  }
2507
2717
  async handleGetAppMetadataRequest({ payload }) {
2508
- const appMetadata = await window.fdc3?.getAppMetadata(payload.app);
2718
+ if (!window.fdc3) {
2719
+ return { error: "ApiTimeout" };
2720
+ }
2721
+ const appMetadata = await window.fdc3.getAppMetadata(payload.app);
2509
2722
  return { appMetadata };
2510
2723
  }
2511
- async handleGetInfoRequest(request) {
2512
- const implementationMetadata = await window.fdc3?.getInfo();
2724
+ async handleGetInfoRequest(_request) {
2725
+ if (!window.fdc3) {
2726
+ return { error: "ApiTimeout" };
2727
+ }
2728
+ const info = await window.fdc3.getInfo();
2729
+ if (!info) {
2730
+ return { error: "NoResultReturned" };
2731
+ }
2732
+ const implementationMetadata = { ...info, appMetadata: this.myAppMetadata };
2513
2733
  return { implementationMetadata };
2514
2734
  }
2515
2735
  async handleOpenRequest({ payload }) {
2516
- const appIdentifier = await window.fdc3?.open(payload.app, payload.context);
2517
- return { appIdentifier };
2736
+ if (!window.fdc3) {
2737
+ return { error: "ApiTimeout" };
2738
+ }
2739
+ const enrichedMetadata = buildEnrichedMetadata(payload.metadata, this.myAppMetadata);
2740
+ try {
2741
+ const appIdentifier = await window.fdc3.open(payload.app, payload.context, enrichedMetadata);
2742
+ return { appIdentifier };
2743
+ }
2744
+ catch (error) {
2745
+ const errorMsg = error instanceof Error ? error.message : "ApiTimeout";
2746
+ return { error: errorMsg };
2747
+ }
2518
2748
  }
2519
- async handleHeartbeatAcknowledgementRequest({ heartbeatEventUuid }) {
2520
- return { alive: true, heartbeatEventUuid };
2749
+ handleHeartbeatAcknowledgementRequest({ heartbeatEventUuid }) {
2750
+ return Promise.resolve({ alive: true, heartbeatEventUuid });
2521
2751
  }
2522
2752
  decorateResponse({ payload, request, responseUuid }) {
2523
2753
  return {
@@ -2531,38 +2761,165 @@
2531
2761
  payload
2532
2762
  };
2533
2763
  }
2764
+ async handleCloseRequest(_request) {
2765
+ const error = "ApiTimeout";
2766
+ if (!window.fdc3) {
2767
+ return { error };
2768
+ }
2769
+ try {
2770
+ await window.fdc3.close();
2771
+ return {};
2772
+ }
2773
+ catch {
2774
+ return { error };
2775
+ }
2776
+ }
2534
2777
  }
2535
2778
 
2536
- var WCPMessageTypes;
2537
- (function (WCPMessageTypes) {
2538
- WCPMessageTypes["WCP1Hello"] = "WCP1Hello";
2539
- WCPMessageTypes["WCP2LoadUrl"] = "WCP2LoadUrl";
2540
- WCPMessageTypes["WCP3Handshake"] = "WCP3Handshake";
2541
- WCPMessageTypes["WCP4ValidateAppIdentity"] = "WCP4ValidateAppIdentity";
2542
- WCPMessageTypes["WCP5ValidateAppIdentityFailedResponse"] = "WCP5ValidateAppIdentityFailedResponse";
2543
- WCPMessageTypes["WCP5ValidateAppIdentityResponse"] = "WCP5ValidateAppIdentityResponse";
2544
- WCPMessageTypes["WCP6Goodbye"] = "WCP6Goodbye";
2545
- })(WCPMessageTypes || (WCPMessageTypes = {}));
2546
- const FDC3_READY_TIMEOUT = 120 * 1000;
2547
- const DESKTOP_AGENT_NAME = "io.Connect Browser";
2548
- const channelTypes = ["user", "app", "private"];
2549
- const defaultChannelsProps = ["id", "type", "broadcast", "addContextListener", "getCurrentContext"];
2779
+ /**
2780
+ * SPDX-License-Identifier: Apache-2.0
2781
+ * Copyright FINOS FDC3 contributors - see NOTICE file
2782
+ */
2783
+ /**
2784
+ * Contains constants representing the errors that can be encountered when trying to connect to a web-based Desktop Agent with the getAgent function.
2785
+ */
2786
+ var AgentError;
2787
+ (function (AgentError) {
2788
+ /** Returned if no Desktop Agent was found by any means available or
2789
+ * if the Agent previously connected to is not contactable on a
2790
+ * subsequent connection attempt.*/
2791
+ AgentError["AgentNotFound"] = "AgentNotFound";
2792
+ /** Returned if validation of the app identity by the Desktop Agent
2793
+ * Failed or the app is not being allowed to connect to the Desktop Agent
2794
+ * for another reason. */
2795
+ AgentError["AccessDenied"] = "AccessDenied";
2796
+ /** Returned if an error or exception occurs while trying to set
2797
+ * up communication with a Desktop Agent. */
2798
+ AgentError["ErrorOnConnect"] = "ErrorOnConnect";
2799
+ /** Returned if the failover function is not a function, or it did not
2800
+ * resolve to one of the allowed types. */
2801
+ AgentError["InvalidFailover"] = "InvalidFailover";
2802
+ /** Returned if an API call rejects after a timeout. Used where an API call
2803
+ * is not aligned to another error enumeration.
2804
+ */
2805
+ AgentError["ApiTimeout"] = "ApiTimeout";
2806
+ })(AgentError || (AgentError = {}));
2807
+ /** Constants representing the errors that can be encountered when calling the `open` method on the DesktopAgent object (`fdc3`). */
2808
+ var OpenError;
2809
+ (function (OpenError) {
2810
+ /** Returned if the specified application is not found.*/
2811
+ OpenError["AppNotFound"] = "AppNotFound";
2812
+ /** Returned if the specified application fails to launch correctly.*/
2813
+ OpenError["ErrorOnLaunch"] = "ErrorOnLaunch";
2814
+ /** Returned if the specified application launches and initializes FDC3, but fails to add a context listener in order to receive the context passed to the `fdc3.open` call.*/
2815
+ OpenError["AppTimeout"] = "AppTimeout";
2816
+ /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
2817
+ OpenError["ResolverUnavailable"] = "ResolverUnavailable";
2818
+ /** 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.*/
2819
+ OpenError["MalformedContext"] = "MalformedContext";
2820
+ /** @experimental Returned if the specified Desktop Agent is not found, via a connected Desktop Agent Bridge.*/
2821
+ OpenError["DesktopAgentNotFound"] = "DesktopAgentNotFound";
2822
+ /** Returned if the specified application launches but fails to initialize FDC3 in time, regardless of whether context was passed to `fdc3.open`. Opening a non-FDC3 application will result in this error.*/
2823
+ OpenError["ApiTimeout"] = "ApiTimeout";
2824
+ /** Returned when incorrect arguments are passed to API calls.*/
2825
+ OpenError["InvalidArguments"] = "InvalidArguments";
2826
+ })(OpenError || (OpenError = {}));
2827
+ /** Constants representing the errors that can be encountered when calling the `close` method on the DesktopAgent object (`fdc3`). */
2828
+ var CloseError;
2829
+ (function (CloseError) {
2830
+ /** Returned if the Desktop Agent cannot close the app's window or frame. */
2831
+ CloseError["ErrorOnClose"] = "ErrorOnClose";
2832
+ /** Returned if a timeout occurs before a call to close is resolved for any reason other than the app being closed. */
2833
+ CloseError["ApiTimeout"] = "ApiTimeout";
2834
+ })(CloseError || (CloseError = {}));
2835
+ /** Constants representing the errors that can be encountered when calling the `findIntent`, `findIntentsByContext`, `raiseIntent` or `raiseIntentForContext` methods on the DesktopAgent (`fdc3`). */
2836
+ var ResolveError;
2837
+ (function (ResolveError) {
2838
+ /** SHOULD be returned if no apps are available that can resolve the intent and context combination.*/
2839
+ ResolveError["NoAppsFound"] = "NoAppsFound";
2840
+ /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
2841
+ ResolveError["ResolverUnavailable"] = "ResolverUnavailable";
2842
+ /** Returned if the user cancelled the resolution request, for example by closing or cancelling a resolver UI.*/
2843
+ ResolveError["UserCancelled"] = "UserCancelledResolution";
2844
+ /** 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.*/
2845
+ ResolveError["ResolverTimeout"] = "ResolverTimeout";
2846
+ /** Returned if a specified target application is not available or a new instance of it cannot be opened. */
2847
+ ResolveError["TargetAppUnavailable"] = "TargetAppUnavailable";
2848
+ /** Returned if a specified target application instance is not available, for example because it has been closed. */
2849
+ ResolveError["TargetInstanceUnavailable"] = "TargetInstanceUnavailable";
2850
+ /** 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.*/
2851
+ ResolveError["IntentDeliveryFailed"] = "IntentDeliveryFailed";
2852
+ /** 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.*/
2853
+ ResolveError["MalformedContext"] = "MalformedContext";
2854
+ /** Returned if `fdc3.addIntentListener` is called for a specified intent that the application has already added a listener for and has not subsequently removed it. */
2855
+ ResolveError["IntentListenerConflict"] = "IntentListenerConflict";
2856
+ /** @experimental Returned if the specified Desktop Agent is not found, via a connected Desktop Agent Bridge.*/
2857
+ ResolveError["DesktopAgentNotFound"] = "DesktopAgentNotFound";
2858
+ /** Returned if a timeout occurs before the API call is resolved for any reason other than the resolver timing out (use ResolverTimeout) or an app launched by a raiseIntent function doesn't add its intent listener in time (use IntentDeliveryFailed).*/
2859
+ ResolveError["ApiTimeout"] = "ApiTimeout";
2860
+ /** Returned when incorrect arguments are passed to API calls.*/
2861
+ ResolveError["InvalidArguments"] = "InvalidArguments";
2862
+ })(ResolveError || (ResolveError = {}));
2863
+ var ResultError;
2864
+ (function (ResultError) {
2865
+ /** Returned if the intent handler exited without returning a valid result (a promise resolving to a Context, Channel object or void). */
2866
+ ResultError["NoResultReturned"] = "NoResultReturned";
2867
+ /** Returned if the Intent handler function processing the raised intent throws an error or rejects the Promise it returned. */
2868
+ ResultError["IntentHandlerRejected"] = "IntentHandlerRejected";
2869
+ /** Returned if a timeout occurs before the getResult() API call is resolved.*/
2870
+ ResultError["ApiTimeout"] = "ApiTimeout";
2871
+ })(ResultError || (ResultError = {}));
2872
+ var ChannelError;
2873
+ (function (ChannelError) {
2874
+ /** Returned if the specified channel is not found when attempting to join a channel via the `joinUserChannel` function of the DesktopAgent (`fdc3`).*/
2875
+ ChannelError["NoChannelFound"] = "NoChannelFound";
2876
+ /** 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. */
2877
+ ChannelError["AccessDenied"] = "AccessDenied";
2878
+ /** SHOULD be returned when a channel cannot be created or retrieved via the `getOrCreateChannel` method of the DesktopAgent (`fdc3`).*/
2879
+ ChannelError["CreationFailed"] = "CreationFailed";
2880
+ /** 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.*/
2881
+ ChannelError["MalformedContext"] = "MalformedContext";
2882
+ /** Returned if a timeout occurs before any Channel related API call is resolved.*/
2883
+ ChannelError["ApiTimeout"] = "ApiTimeout";
2884
+ /** Returned when incorrect arguments are passed to API calls.*/
2885
+ ChannelError["InvalidArguments"] = "InvalidArguments";
2886
+ })(ChannelError || (ChannelError = {}));
2887
+ var BridgingError;
2888
+ (function (BridgingError) {
2889
+ /** @experimental Returned if a Desktop Agent did not return a response, via Desktop Agent Bridging, within the alloted timeout. */
2890
+ BridgingError["ResponseTimedOut"] = "ResponseToBridgeTimedOut";
2891
+ /** @experimental Returned if a Desktop Agent that has been targeted by a particular request has been disconnected from the Bridge before a response has been received from it. */
2892
+ BridgingError["AgentDisconnected"] = "AgentDisconnected";
2893
+ /** @experimental Returned for FDC3 API calls that are specified with arguments indicating that a remote Desktop agent should be targeted (e.g. raiseIntent with an app on a remote DesktopAgent targeted), when the local Desktop Agent is not connected to a bridge. */
2894
+ BridgingError["NotConnectedToBridge"] = "NotConnectedToBridge";
2895
+ /** @experimental Returned if a message to a Bridge deviates from the schema for that message sufficiently that it could not be processed. */
2896
+ BridgingError["MalformedMessage"] = "MalformedMessage";
2897
+ })(BridgingError || (BridgingError = {}));
2898
+
2899
+ const supportedEventTypes = ["userChannelChanged", "contextCleared"];
2550
2900
 
2551
- var ChannelEventToTypeDictionary;
2552
- (function (ChannelEventToTypeDictionary) {
2553
- ChannelEventToTypeDictionary["USER_CHANNEL_CHANGED"] = "userChannelChanged";
2554
- })(ChannelEventToTypeDictionary || (ChannelEventToTypeDictionary = {}));
2901
+ const ChannelEventToTypeDictionary = {
2902
+ "USER_CHANNEL_CHANGED": "userChannelChanged",
2903
+ "CONTEXT_CLEARED": "contextCleared"
2904
+ };
2555
2905
  const privateChannelPrefix = "___privateFDC3Channel___";
2556
2906
 
2557
2907
  class ChannelsController {
2558
2908
  sendBridgeMessage;
2909
+ myAppMetadata;
2559
2910
  logger;
2560
2911
  listenersCollection = {};
2912
+ contextListeners = new Map();
2913
+ eventListeners = new Map();
2914
+ userChannelMemberships = new WeakMap();
2915
+ pendingProxyJoins = new WeakMap();
2916
+ forwardedPrivateEvents = new WeakSet();
2561
2917
  privateChannelsCollection = {};
2562
2918
  operations = {
2563
2919
  addContextListenerRequest: { requestType: "addContextListenerRequest", requestDecoder: addContextListenerRequestDecoder, responseType: "addContextListenerResponse", responseDecoder: addContextListenerResponseDecoder, execute: this.handleAddContextListenerRequest.bind(this) },
2564
2920
  addEventListenerRequest: { requestType: "addEventListenerRequest", requestDecoder: addEventListenerRequestDecoder, responseType: "addEventListenerResponse", responseDecoder: addEventListenerResponseDecoder, execute: this.handleAddEventListenerRequest.bind(this) },
2565
2921
  broadcastRequest: { requestType: "broadcastRequest", responseType: "broadcastResponse", requestDecoder: broadcastRequestDecoder, responseDecoder: broadcastResponseDecoder, execute: this.handleBroadcastRequest.bind(this) },
2922
+ clearContextRequest: { requestType: "clearContextRequest", requestDecoder: clearContextRequestDecoder, responseType: "clearContextResponse", responseDecoder: clearContextResponseDecoder, execute: this.handleClearContextRequest.bind(this) },
2566
2923
  contextListenerUnsubscribeRequest: { requestType: "contextListenerUnsubscribeRequest", requestDecoder: contextListenerUnsubscribeRequestDecoder, responseType: "contextListenerUnsubscribeResponse", responseDecoder: contextListenerUnsubscribeResponseDecoder, execute: this.handleUnsubscribeRequest.bind(this) },
2567
2924
  createPrivateChannelRequest: { requestType: "createPrivateChannelRequest", requestDecoder: createPrivateChannelRequestDecoder, responseType: "createPrivateChannelResponse", responseDecoder: createPrivateChannelResponseDecoder, execute: this.handleCreatePrivateChannelRequest.bind(this) },
2568
2925
  eventListenerUnsubscribeRequest: { requestType: "eventListenerUnsubscribeRequest", requestDecoder: eventListenerUnsubscribeRequestDecoder, responseType: "eventListenerUnsubscribeResponse", responseDecoder: eventListenerUnsubscribeResponseDecoder, execute: this.handleUnsubscribeRequest.bind(this) },
@@ -2576,8 +2933,9 @@
2576
2933
  privateChannelDisconnectRequest: { requestType: "privateChannelDisconnectRequest", requestDecoder: privateChannelDisconnectRequestDecoder, responseType: "privateChannelDisconnectResponse", responseDecoder: privateChannelDisconnectResponseDecoder, execute: this.handlePrivateChannelDisconnectRequest.bind(this) },
2577
2934
  privateChannelUnsubscribeEventListenerRequest: { requestType: "privateChannelUnsubscribeEventListenerRequest", requestDecoder: privateChannelUnsubscribeEventListenerRequestDecoder, responseType: "privateChannelUnsubscribeEventListenerResponse", responseDecoder: privateChannelUnsubscribeEventListenerResponseDecoder, execute: this.handlePrivateChannelUnsubscribeEventListenerRequest.bind(this) }
2578
2935
  };
2579
- constructor(sendBridgeMessage, logger) {
2936
+ constructor(sendBridgeMessage, myAppMetadata, logger) {
2580
2937
  this.sendBridgeMessage = sendBridgeMessage;
2938
+ this.myAppMetadata = myAppMetadata;
2581
2939
  this.logger = logger;
2582
2940
  }
2583
2941
  async handleControl(request) {
@@ -2612,105 +2970,317 @@
2612
2970
  this.logger?.info(`Returning response: ${JSON.stringify(response)}`);
2613
2971
  return response;
2614
2972
  }
2973
+ async handlePostResponse(request) {
2974
+ const operation = this.operations[request.type];
2975
+ await operation.postResponse?.(request);
2976
+ }
2615
2977
  addPrivateChannel(privateChannel) {
2616
2978
  this.logger?.info(`addPrivateChannel called with channel id: ${privateChannel.id}, type: ${privateChannel.type}`);
2617
2979
  this.privateChannelsCollection[privateChannel.id] = privateChannel;
2618
2980
  }
2619
2981
  async handleAddContextListenerRequest({ payload }) {
2982
+ if (!window.fdc3) {
2983
+ return { error: "AccessDenied" };
2984
+ }
2620
2985
  const listenerUUID = nanoid();
2986
+ const agent = window.fdc3;
2621
2987
  const channel = payload.channelId ? await this.getChannelById(payload.channelId) : null;
2622
- const handler = async (context, metadata) => {
2988
+ const initialChannel = payload.channelId == null ? await agent.getCurrentChannel?.() : null;
2989
+ const registrationMembership = this.userChannelMemberships.get(agent);
2990
+ const handler = async (context, metadata, replayChannelId, isInitialReplay) => {
2991
+ if (!window.fdc3) {
2992
+ return { error: "AccessDenied" };
2993
+ }
2623
2994
  this.logger?.info(`addContextListener handler invoked with context: ${JSON.stringify(context)} and metadata: ${JSON.stringify(metadata)}`);
2624
- const eventUuid = nanoid();
2625
- const channelId = !payload.channelId || channel?.type === "user"
2626
- ? (await window.fdc3?.getCurrentChannel())?.id ?? null
2627
- : payload.channelId;
2628
- const broadcastEventMsg = {
2629
- type: "broadcastEvent",
2630
- meta: {
2631
- eventUuid,
2632
- timestamp: new Date()
2633
- },
2634
- payload: {
2635
- channelId,
2636
- context,
2637
- originatingApp: {
2638
- appId: metadata?.source.appId ?? "",
2639
- instanceId: metadata?.source.instanceId,
2640
- desktopAgent: DESKTOP_AGENT_NAME
2641
- }
2642
- }
2643
- };
2644
- this.logger?.info(`Sending 'broadcastEvent' message: ${JSON.stringify(broadcastEventMsg)}`);
2645
- this.sendBridgeMessage(broadcastEventMsg);
2995
+ const hasDesktopListener = Array.from(this.contextListeners.values()).some((listener) => listener.agent === agent && listener.channelId === null);
2996
+ let currentChannel = null;
2997
+ if (hasDesktopListener) {
2998
+ currentChannel = await agent.getCurrentChannel();
2999
+ }
3000
+ const currentChannelId = currentChannel?.id ?? null;
3001
+ const channelId = payload.channelId ?? currentChannelId;
3002
+ if (payload.channelId == null && isInitialReplay) {
3003
+ await this.replayExternalChannelContext(listenerUUID, agent, currentChannel, replayChannelId, initialChannel?.id, registrationMembership);
3004
+ return;
3005
+ }
3006
+ if (!this.hasMatchingContextListener(listenerUUID, agent, channelId, context.type, currentChannelId)) {
3007
+ return;
3008
+ }
3009
+ const membership = this.userChannelMemberships.get(agent);
3010
+ if (membership?.channelId === channelId) {
3011
+ await membership.replay;
3012
+ }
3013
+ this.sendContextEvent(channelId, context, metadata);
2646
3014
  };
2647
- const addContextListenerInterfaceMsg = channel ? "channel '" + channel.id + "'" : "fdc3";
2648
- this.logger?.info(`Adding context listener on ${addContextListenerInterfaceMsg} interface for context type ${payload.contextType ?? null}`);
2649
- const listener = await (channel ?? window.fdc3)?.addContextListener(payload.contextType ?? null, handler);
2650
- this.listenersCollection[listenerUUID] = listener;
3015
+ const addContextListenerInterfaceMsg = channel ? `channel '${channel.id}'` : "fdc3";
3016
+ const contextTypesMsg = payload.contextTypes ? JSON.stringify(payload.contextTypes) : JSON.stringify(payload.contextType ?? null);
3017
+ this.logger?.info(`Adding context listener on ${addContextListenerInterfaceMsg} interface for context type(s) ${contextTypesMsg}`);
3018
+ const target = channel ?? window.fdc3;
3019
+ const registration = { agent, channelId: payload.channelId ?? null, types: payload.contextTypes ?? payload.contextType ?? null, isActive: false };
3020
+ this.contextListeners.set(listenerUUID, registration);
3021
+ try {
3022
+ const listener = await (payload.contextTypes != null
3023
+ ? target.addContextListener(payload.contextTypes, handler)
3024
+ : target.addContextListener(payload.contextType ?? null, handler));
3025
+ this.listenersCollection[listenerUUID] = listener;
3026
+ registration.isActive = true;
3027
+ }
3028
+ catch (error) {
3029
+ this.contextListeners.delete(listenerUUID);
3030
+ throw error;
3031
+ }
2651
3032
  return { listenerUUID };
2652
3033
  }
3034
+ updateUserChannelMembership(agent, channelId) {
3035
+ const previous = this.userChannelMemberships.get(agent);
3036
+ if (previous?.channelId === channelId) {
3037
+ return previous;
3038
+ }
3039
+ const pendingJoin = this.pendingProxyJoins.get(agent);
3040
+ const membership = pendingJoin?.channelId === channelId
3041
+ ? pendingJoin
3042
+ : { channelId, isProxyRequested: false };
3043
+ this.userChannelMemberships.set(agent, membership);
3044
+ return membership;
3045
+ }
3046
+ async replayExternalChannelContext(listenerUUID, agent, channel, replayChannelId, initialChannelId, registrationMembership) {
3047
+ if (!this.contextListeners.has(listenerUUID) || !channel) {
3048
+ return;
3049
+ }
3050
+ if (replayChannelId != null && replayChannelId !== channel.id) {
3051
+ return;
3052
+ }
3053
+ if (this.shouldSuppressContextReplay(agent, channel.id, initialChannelId, registrationMembership)) {
3054
+ return;
3055
+ }
3056
+ const membership = this.updateUserChannelMembership(agent, channel.id);
3057
+ membership.replay ??= this.readContextReplay(agent, channel, listenerUUID).then((contexts) => {
3058
+ if (window.fdc3 !== agent || this.userChannelMemberships.get(agent) !== membership) {
3059
+ return;
3060
+ }
3061
+ for (const { context, metadata } of contexts) {
3062
+ this.sendContextEvent(channel.id, context, metadata);
3063
+ }
3064
+ }).catch((error) => {
3065
+ membership.replay = undefined;
3066
+ this.logger?.warn(`Could not replay retained context on channel '${channel.id}': ${error}`);
3067
+ });
3068
+ await membership.replay;
3069
+ }
3070
+ async readContextReplay(agent, channel, listenerUUID) {
3071
+ const types = this.getContextReplayTypes(agent, listenerUUID);
3072
+ const latest = await channel.getCurrentContextWithMetadata();
3073
+ const requestedTypes = Array.from(types).filter((type) => type !== null && type !== latest?.context.type);
3074
+ const retained = await Promise.all(requestedTypes.map((type) => channel.getCurrentContextWithMetadata(type)));
3075
+ const contexts = retained.filter((result) => result !== null);
3076
+ if (latest && (types.has(null) || types.has(latest.context.type))) {
3077
+ contexts.push(latest);
3078
+ }
3079
+ return contexts;
3080
+ }
3081
+ getContextReplayTypes(agent, listenerUUID) {
3082
+ const types = new Set();
3083
+ for (const [uuid, listener] of this.contextListeners) {
3084
+ if (listener.agent !== agent || listener.channelId !== null || (!listener.isActive && uuid !== listenerUUID)) {
3085
+ continue;
3086
+ }
3087
+ const listenerTypes = Array.isArray(listener.types) ? listener.types : [listener.types];
3088
+ listenerTypes.forEach((type) => types.add(type));
3089
+ }
3090
+ return types;
3091
+ }
3092
+ sendContextEvent(channelId, context, metadata) {
3093
+ const broadcastEventMsg = {
3094
+ type: "broadcastEvent",
3095
+ meta: {
3096
+ eventUuid: nanoid(),
3097
+ timestamp: new Date()
3098
+ },
3099
+ payload: { channelId, context, metadata }
3100
+ };
3101
+ this.logger?.info(`Sending 'broadcastEvent' message: ${JSON.stringify(broadcastEventMsg)}`);
3102
+ this.sendBridgeMessage(broadcastEventMsg);
3103
+ }
3104
+ shouldSuppressContextReplay(agent, channelId, initialChannelId, registrationMembership) {
3105
+ const membership = this.userChannelMemberships.get(agent);
3106
+ if (this.pendingProxyJoins.get(agent)?.channelId === channelId) {
3107
+ return true;
3108
+ }
3109
+ if (initialChannelId === channelId && membership === registrationMembership) {
3110
+ return true;
3111
+ }
3112
+ return membership?.channelId === channelId && membership.isProxyRequested;
3113
+ }
3114
+ hasMatchingContextListener(listenerUUID, agent, channelId, type, currentChannelId) {
3115
+ for (const [uuid, listener] of this.contextListeners) {
3116
+ if (!listener.isActive && uuid !== listenerUUID) {
3117
+ continue;
3118
+ }
3119
+ const sameType = listener.types === null
3120
+ || listener.types === type
3121
+ || (Array.isArray(listener.types) && listener.types.includes(type));
3122
+ const listenerChannelId = listener.channelId ?? currentChannelId;
3123
+ if (listener.agent === agent && listenerChannelId === channelId && sameType) {
3124
+ return uuid === listenerUUID;
3125
+ }
3126
+ }
3127
+ return false;
3128
+ }
2653
3129
  async getChannelById(id) {
3130
+ if (!window.fdc3) {
3131
+ throw new Error("AccessDenied");
3132
+ }
2654
3133
  const privateChannel = this.privateChannelsCollection[id];
2655
3134
  if (privateChannel) {
2656
3135
  return privateChannel;
2657
3136
  }
2658
- const channel = await window.fdc3?.getOrCreateChannel(id);
3137
+ if (id.startsWith(privateChannelPrefix)) {
3138
+ throw new Error(ChannelError.AccessDenied);
3139
+ }
3140
+ const channel = await window.fdc3.getOrCreateChannel(id);
2659
3141
  return channel;
2660
3142
  }
3143
+ getMatchingEventListenerUUID(agent, scope, channelId, type) {
3144
+ for (const [listenerUUID, listener] of this.eventListeners) {
3145
+ const sameAgent = listener.agent === agent;
3146
+ const sameScope = listener.scope === scope;
3147
+ const sameChannel = listener.channelId === channelId;
3148
+ const sameType = listener.type === null || listener.type === type;
3149
+ if (!sameAgent || !sameScope || !sameChannel || !sameType) {
3150
+ continue;
3151
+ }
3152
+ return listenerUUID;
3153
+ }
3154
+ }
3155
+ hasMatchingEventListener(listenerUUID, agent, scope, channelId, type) {
3156
+ const eventListenerUUID = this.getMatchingEventListenerUUID(agent, scope, channelId, type);
3157
+ return !eventListenerUUID || eventListenerUUID === listenerUUID;
3158
+ }
2661
3159
  async handleAddEventListenerRequest({ payload }) {
3160
+ if (!window.fdc3) {
3161
+ return { error: ChannelError.AccessDenied };
3162
+ }
3163
+ if (payload.channelId && payload.type === "USER_CHANNEL_CHANGED") {
3164
+ this.logger?.error("Event 'userChannelChanged' cannot be listened to on a specific channel");
3165
+ return { error: ChannelError.InvalidArguments };
3166
+ }
2662
3167
  const listenerUUID = nanoid();
2663
- const handler = (event) => {
3168
+ const agent = window.fdc3;
3169
+ const handler = this.getEventHandler(listenerUUID, agent, payload);
3170
+ const type = payload.type ? ChannelEventToTypeDictionary[payload.type] : null;
3171
+ const listener = await (payload.channelId
3172
+ ? (await this.getChannelById(payload.channelId)).addEventListener(type, handler)
3173
+ : window.fdc3.addEventListener(type, handler));
3174
+ this.listenersCollection[listenerUUID] = listener;
3175
+ this.eventListeners.set(listenerUUID, { agent, scope: payload.channelId ? "channel" : "desktop", channelId: payload.channelId ?? null, type });
3176
+ return { listenerUUID };
3177
+ }
3178
+ getEventHandler(listenerUUID, agent, payload) {
3179
+ const scope = payload.channelId ? "channel" : "desktop";
3180
+ const channelId = payload.channelId ?? null;
3181
+ return (event) => {
3182
+ if (scope === "desktop" && event.type === "userChannelChanged") {
3183
+ this.updateUserChannelMembership(agent, event.details.currentChannelId ?? null);
3184
+ }
3185
+ if (scope === "desktop" && event.type === "contextCleared" && this.getMatchingEventListenerUUID(agent, "channel", event.details.channelId, event.type)) {
3186
+ return;
3187
+ }
3188
+ const hasMatching = this.hasMatchingEventListener(listenerUUID, agent, scope, channelId, event.type);
3189
+ if (!hasMatching) {
3190
+ return;
3191
+ }
2664
3192
  this.logger?.info(`addEventListener's callback invoked with event: ${JSON.stringify(event)}`);
2665
- const eventUuid = nanoid();
2666
- if (event.type !== "userChannelChanged") {
3193
+ if (!this.checkIfEventSupported(event, payload)) {
2667
3194
  return;
2668
3195
  }
2669
- const currentChannelId = event.details.currentChannelId ?? null;
2670
- const response = {
2671
- type: "channelChangedEvent",
2672
- meta: {
2673
- eventUuid,
2674
- timestamp: new Date()
2675
- },
2676
- payload: {
2677
- currentChannelId,
2678
- newChannelId: currentChannelId,
2679
- }
2680
- };
2681
- this.logger?.info(`Sending 'channelChangedEvent' message: ${JSON.stringify(response)}`);
3196
+ let response;
3197
+ if (event.type === "userChannelChanged") {
3198
+ response = this.getChannelChangedEvent(event);
3199
+ }
3200
+ if (event.type === "contextCleared") {
3201
+ response = this.getContextClearedEvent(event);
3202
+ }
3203
+ if (!response) {
3204
+ this.logger?.warn(`Unsupported event type: ${event.type}`);
3205
+ return;
3206
+ }
3207
+ this.logger?.info(`Sending '${response.type}' message: ${JSON.stringify(response)}`);
2682
3208
  this.sendBridgeMessage(response);
2683
3209
  };
2684
- this.logger?.info(`Adding event listener for type ${payload.type ?? null} on fdc3 interface`);
2685
- const type = this.getAddEventListenerTypeByRequestPayloadType(payload.type);
2686
- const listener = await window.fdc3.addEventListener(type, handler);
2687
- this.listenersCollection[listenerUUID] = listener;
2688
- return { listenerUUID };
2689
3210
  }
2690
- getAddEventListenerTypeByRequestPayloadType(requestType) {
2691
- if (!requestType) {
2692
- return null;
3211
+ checkIfEventSupported(event, payload) {
3212
+ if (!supportedEventTypes.includes(event.type)) {
3213
+ this.logger?.warn(`Unsupported event type: ${event.type}`);
3214
+ return false;
2693
3215
  }
2694
- return ChannelEventToTypeDictionary[requestType] ?? null;
3216
+ if (payload.channelId && event.type === "userChannelChanged") {
3217
+ this.logger?.warn("Event 'userChannelChanged' cannot be listened to on a specific channel");
3218
+ return false;
3219
+ }
3220
+ return true;
3221
+ }
3222
+ getChannelChangedEvent(event) {
3223
+ const currentChannelId = event.details.currentChannelId ?? null;
3224
+ const response = {
3225
+ type: "channelChangedEvent",
3226
+ meta: {
3227
+ eventUuid: nanoid(),
3228
+ timestamp: new Date()
3229
+ },
3230
+ payload: {
3231
+ currentChannelId,
3232
+ newChannelId: currentChannelId,
3233
+ }
3234
+ };
3235
+ return response;
3236
+ }
3237
+ getContextClearedEvent(event) {
3238
+ const response = {
3239
+ type: "contextClearedEvent",
3240
+ meta: {
3241
+ eventUuid: nanoid(),
3242
+ timestamp: new Date()
3243
+ },
3244
+ payload: {
3245
+ channelId: event.details.channelId,
3246
+ contextType: event.details.contextType ?? null
3247
+ }
3248
+ };
3249
+ return response;
2695
3250
  }
2696
3251
  async handleBroadcastRequest({ payload }) {
2697
- const { channelId, context } = payload;
3252
+ const { channelId, context, metadata } = payload;
3253
+ const channel = await this.getChannelById(channelId);
3254
+ const enrichedMetadata = buildEnrichedMetadata(metadata, this.myAppMetadata);
3255
+ await (channel ?? window.fdc3)?.broadcast(context, enrichedMetadata);
3256
+ return {};
3257
+ }
3258
+ async handleClearContextRequest({ payload }) {
3259
+ const { channelId, contextType } = payload;
2698
3260
  const channel = await this.getChannelById(channelId);
2699
- await (channel ?? window.fdc3)?.broadcast(context);
3261
+ if (!channel) {
3262
+ return { error: "NoChannelFound" };
3263
+ }
3264
+ await channel.clearContext(contextType ?? undefined);
2700
3265
  return {};
2701
3266
  }
2702
3267
  async handleUnsubscribeRequest({ payload }) {
2703
3268
  const listener = this.listenersCollection[payload.listenerUUID];
2704
3269
  if (!listener) {
2705
- return { error: "MalformedMessage", reason: `Cannot find listener with listenerUUID: ${payload.listenerUUID}` };
3270
+ return { error: ChannelError.AccessDenied };
2706
3271
  }
2707
3272
  this.logger?.info(`Unsubscribing listener with UUID: ${payload.listenerUUID}`);
2708
3273
  await listener.unsubscribe();
2709
3274
  delete this.listenersCollection[payload.listenerUUID];
3275
+ this.eventListeners.delete(payload.listenerUUID);
3276
+ this.contextListeners.delete(payload.listenerUUID);
2710
3277
  return {};
2711
3278
  }
2712
3279
  async handleCreatePrivateChannelRequest() {
2713
- const privateChannel = await window.fdc3?.createPrivateChannel();
3280
+ if (!window.fdc3) {
3281
+ return { error: "AccessDenied" };
3282
+ }
3283
+ const privateChannel = await window.fdc3.createPrivateChannel();
2714
3284
  if (!privateChannel) {
2715
3285
  return { error: "CreationFailed" };
2716
3286
  }
@@ -2719,36 +3289,83 @@
2719
3289
  return { privateChannel: pureChannel };
2720
3290
  }
2721
3291
  async handleGetCurrentChannelRequest() {
2722
- const channel = await window.fdc3?.getCurrentChannel();
3292
+ if (!window.fdc3) {
3293
+ return { error: "AccessDenied" };
3294
+ }
3295
+ const channel = await window.fdc3.getCurrentChannel();
2723
3296
  const pureChannel = JSON.parse(JSON.stringify(channel));
2724
3297
  return { channel: pureChannel };
2725
3298
  }
2726
3299
  async handleGetCurrentContextRequest({ payload }) {
2727
- const channel = await window.fdc3?.getOrCreateChannel(payload.channelId);
3300
+ if (!window.fdc3) {
3301
+ return { error: "AccessDenied" };
3302
+ }
3303
+ const channel = await this.getChannelById(payload.channelId);
3304
+ if (!channel) {
3305
+ return { error: "NoChannelFound" };
3306
+ }
2728
3307
  const contextType = payload.contextType ?? undefined;
2729
- const context = await channel?.getCurrentContext(contextType);
2730
- return { context };
3308
+ const contextWithMetadata = await channel.getCurrentContextWithMetadata(contextType);
3309
+ return {
3310
+ context: contextWithMetadata?.context ?? null,
3311
+ metadata: contextWithMetadata?.metadata ?? null
3312
+ };
2731
3313
  }
2732
3314
  async handleGetOrCreateChannelRequest({ payload }) {
3315
+ if (!window.fdc3) {
3316
+ return { error: "AccessDenied" };
3317
+ }
2733
3318
  const isPrivateChannel = this.privateChannelsCollection[payload.channelId] ?? payload.channelId.startsWith(privateChannelPrefix);
2734
3319
  if (isPrivateChannel) {
2735
3320
  return { error: "AccessDenied" };
2736
3321
  }
2737
- const channel = await window.fdc3?.getOrCreateChannel(payload.channelId);
3322
+ const channel = await window.fdc3.getOrCreateChannel(payload.channelId);
2738
3323
  const pureChannel = JSON.parse(JSON.stringify(channel));
2739
3324
  return { channel: pureChannel };
2740
3325
  }
2741
3326
  async handleGetUserChannelsRequest() {
2742
- const userChannels = await window.fdc3?.getUserChannels() ?? [];
3327
+ if (!window.fdc3) {
3328
+ return { error: "AccessDenied" };
3329
+ }
3330
+ const userChannels = await window.fdc3.getUserChannels() ?? [];
2743
3331
  const pureChannels = userChannels.map((ch) => JSON.parse(JSON.stringify(ch)));
2744
3332
  return { userChannels: pureChannels };
2745
3333
  }
2746
3334
  async handleJoinUserChannelRequest({ payload }) {
2747
- await window.fdc3?.joinUserChannel(payload.channelId);
3335
+ if (!window.fdc3) {
3336
+ return { error: "AccessDenied" };
3337
+ }
3338
+ const agent = window.fdc3;
3339
+ const previous = this.userChannelMemberships.get(agent);
3340
+ const membership = { channelId: payload.channelId, isProxyRequested: true };
3341
+ this.userChannelMemberships.set(agent, membership);
3342
+ this.pendingProxyJoins.set(agent, membership);
3343
+ try {
3344
+ await agent.joinUserChannel(payload.channelId);
3345
+ }
3346
+ catch (error) {
3347
+ if (this.userChannelMemberships.get(agent) === membership) {
3348
+ this.userChannelMemberships.delete(agent);
3349
+ if (previous) {
3350
+ this.userChannelMemberships.set(agent, previous);
3351
+ }
3352
+ }
3353
+ throw error;
3354
+ }
3355
+ finally {
3356
+ if (this.pendingProxyJoins.get(agent) === membership) {
3357
+ this.pendingProxyJoins.delete(agent);
3358
+ }
3359
+ }
2748
3360
  return {};
2749
3361
  }
2750
3362
  async handleLeaveCurrentChannel(request) {
2751
- await window.fdc3?.leaveCurrentChannel();
3363
+ if (!window.fdc3) {
3364
+ return { error: "AccessDenied" };
3365
+ }
3366
+ const agent = window.fdc3;
3367
+ await agent.leaveCurrentChannel();
3368
+ this.updateUserChannelMembership(agent, null);
2752
3369
  return {};
2753
3370
  }
2754
3371
  async handlePrivateChannelAddEventListenerRequest({ payload }) {
@@ -2758,30 +3375,43 @@
2758
3375
  if (!privateChannel) {
2759
3376
  return { error: "NoChannelFound" };
2760
3377
  }
3378
+ const listenerUUID = nanoid();
3379
+ const agent = window.fdc3 ?? privateChannel;
2761
3380
  const handler = (event) => {
2762
3381
  this.logger?.info(`Received event: ${JSON.stringify(event)}`);
3382
+ if (listenerType === null && event.type === "contextCleared") {
3383
+ return;
3384
+ }
3385
+ if (event.type === "contextCleared" && this.getMatchingEventListenerUUID(agent, "channel", privateChannelId, event.type)) {
3386
+ return;
3387
+ }
2763
3388
  if (listenerType && listenerType !== event.type) {
2764
3389
  this.logger?.info(`Listener type from private channel addEventListenerRequest '${listenerType}' does not match the event type '${event.type}'. Handler won't be invoked...`);
2765
3390
  return;
2766
3391
  }
2767
- const eventUuid = nanoid();
2768
- const responseType = {
2769
- type: this.getPrivateChannelResponseType(event.type),
2770
- meta: {
2771
- eventUuid,
2772
- timestamp: new Date()
2773
- },
2774
- payload: {
2775
- contextType: event.details?.contextType,
2776
- privateChannelId: payload.privateChannelId
2777
- }
2778
- };
2779
- this.logger?.info(`Sending private channel event response: ${JSON.stringify(responseType)}`);
2780
- this.sendBridgeMessage(responseType);
3392
+ if (this.forwardedPrivateEvents.has(event)) {
3393
+ return;
3394
+ }
3395
+ const response = event.type === "contextCleared"
3396
+ ? this.getContextClearedEvent(event)
3397
+ : {
3398
+ type: this.getPrivateChannelResponseType(event.type),
3399
+ meta: {
3400
+ eventUuid: nanoid(),
3401
+ timestamp: new Date()
3402
+ },
3403
+ payload: {
3404
+ contextType: event.details?.contextType,
3405
+ privateChannelId
3406
+ }
3407
+ };
3408
+ this.logger?.info(`Sending private channel event response: ${JSON.stringify(response)}`);
3409
+ this.forwardedPrivateEvents.add(event);
3410
+ this.sendBridgeMessage(response);
2781
3411
  };
2782
- const listenerUUID = nanoid();
2783
3412
  const listener = await privateChannel.addEventListener(payload.listenerType ?? null, handler);
2784
3413
  this.listenersCollection[listenerUUID] = listener;
3414
+ this.eventListeners.set(listenerUUID, { agent, scope: "private", channelId: privateChannelId, type: listenerType });
2785
3415
  return { listenerUUID };
2786
3416
  }
2787
3417
  async handlePrivateChannelDisconnectRequest({ payload }) {
@@ -2800,6 +3430,7 @@
2800
3430
  }
2801
3431
  await listener.unsubscribe();
2802
3432
  delete this.listenersCollection[payload.listenerUUID];
3433
+ this.eventListeners.delete(payload.listenerUUID);
2803
3434
  return {};
2804
3435
  }
2805
3436
  decorateResponse({ request, payload, responseUuid }) {
@@ -2848,9 +3479,7 @@
2848
3479
  this._messageChannel?.port1.postMessage(data);
2849
3480
  }
2850
3481
  globalMessageHandler(event) {
2851
- const parentURL = document.referrer;
2852
- const origin = new URL(parentURL).origin;
2853
- if (event.origin !== origin) {
3482
+ if (window.parent === window || event.source !== window.parent) {
2854
3483
  return;
2855
3484
  }
2856
3485
  if (event.data?.type === WCPMessageTypes.WCP1Hello) {
@@ -2891,6 +3520,10 @@
2891
3520
  const result = await this.ioc.domainsController.handleMessage(event.data);
2892
3521
  this.logMessage({ level: "info", message: `Sending response message: ${JSON.stringify(result)}` });
2893
3522
  this.sendMessage(result);
3523
+ if (result.payload.error !== undefined) {
3524
+ return;
3525
+ }
3526
+ await this.ioc.domainsController.handlePostResponse(event.data);
2894
3527
  }
2895
3528
  async handleAppIdentityValidationRequest(data) {
2896
3529
  const decodedRequest = wcp4ValidateAppIdentityDecoder.run(data);
@@ -2910,6 +3543,10 @@
2910
3543
  this.cleanSetup();
2911
3544
  return;
2912
3545
  }
3546
+ this.ioc.myAppMetadata = {
3547
+ appId: validationResult.appId,
3548
+ instanceId: this.ioController.io?.interop.instance.instance,
3549
+ };
2913
3550
  await this.sendValidationSuccess(data.meta.connectionAttemptUuid, validationResult.appId);
2914
3551
  this.logMessage({ level: "info", message: `App validation is successful. Connection is completed` });
2915
3552
  this._connectionCompleted = true;
@@ -3036,10 +3673,14 @@
3036
3673
  }
3037
3674
  return result;
3038
3675
  }
3676
+ async handlePostResponse(data) {
3677
+ const domain = Object.values(this.domains).find((domain) => domain.requestTypes.includes(data.type));
3678
+ await domain?.controller.handlePostResponse?.(data);
3679
+ }
3039
3680
  setupDomains() {
3040
- const channelsRequestTypes = ["addContextListenerRequest", "addEventListenerRequest", "broadcastRequest", "contextListenerUnsubscribeRequest", "createPrivateChannelRequest", "eventListenerUnsubscribeRequest", "getCurrentChannelRequest", "getCurrentContextRequest", "getOrCreateChannelRequest", "getUserChannelsRequest", "joinUserChannelRequest", "leaveCurrentChannelRequest", "privateChannelAddEventListenerRequest", "privateChannelDisconnectRequest", "privateChannelUnsubscribeEventListenerRequest"];
3681
+ const channelsRequestTypes = ["addContextListenerRequest", "addEventListenerRequest", "broadcastRequest", "clearContextRequest", "contextListenerUnsubscribeRequest", "createPrivateChannelRequest", "eventListenerUnsubscribeRequest", "getCurrentChannelRequest", "getCurrentContextRequest", "getOrCreateChannelRequest", "getUserChannelsRequest", "joinUserChannelRequest", "leaveCurrentChannelRequest", "privateChannelAddEventListenerRequest", "privateChannelDisconnectRequest", "privateChannelUnsubscribeEventListenerRequest"];
3041
3682
  const intentsRequestTypes = ["addIntentListenerRequest", "findIntentRequest", "findIntentsByContextRequest", "intentListenerUnsubscribeRequest", "intentResultRequest", "raiseIntentForContextRequest", "raiseIntentRequest"];
3042
- const applicationsRequestTypes = ["findInstancesRequest", "getAppMetadataRequest", "getInfoRequest", "openRequest", "heartbeatAcknowledgementRequest"];
3683
+ const applicationsRequestTypes = ["findInstancesRequest", "getAppMetadataRequest", "getInfoRequest", "openRequest", "heartbeatAcknowledgementRequest", "closeRequest"];
3043
3684
  this.domains = {
3044
3685
  channels: {
3045
3686
  name: "channels",
@@ -3060,102 +3701,6 @@
3060
3701
  }
3061
3702
  }
3062
3703
 
3063
- const rejectWithErrorObj = (reject, error) => {
3064
- if (error instanceof Error) {
3065
- reject(error.message);
3066
- return;
3067
- }
3068
- if (typeof error === "string") {
3069
- reject(new Error(error));
3070
- return;
3071
- }
3072
- reject(new Error(JSON.stringify(error)));
3073
- };
3074
- const wrapPromise = () => {
3075
- let wrapperResolve;
3076
- let wrapperReject;
3077
- const promise = new Promise((resolve, reject) => {
3078
- wrapperResolve = resolve;
3079
- wrapperReject = reject;
3080
- });
3081
- return { promise, resolve: wrapperResolve, reject: wrapperReject };
3082
- };
3083
- const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => {
3084
- return new Promise((resolve, reject) => {
3085
- const timeout = setTimeout(() => {
3086
- const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`;
3087
- reject(new Error(message));
3088
- }, timeoutMilliseconds);
3089
- promise()
3090
- .then((result) => {
3091
- clearTimeout(timeout);
3092
- resolve(result);
3093
- })
3094
- .catch((error) => {
3095
- clearTimeout(timeout);
3096
- rejectWithErrorObj(reject, error);
3097
- });
3098
- });
3099
- };
3100
- const compareOrigins = (url1, url2) => {
3101
- try {
3102
- const parsedUrl1 = new URL(url1);
3103
- const parsedUrl2 = new URL(url2);
3104
- return parsedUrl1.origin === parsedUrl2.origin;
3105
- }
3106
- catch (e) {
3107
- return false;
3108
- }
3109
- };
3110
- const removeTrailingSlash = (pathname) => {
3111
- return pathname.endsWith("/")
3112
- ? pathname.slice(0, -1)
3113
- : pathname;
3114
- };
3115
- const isRecordUrlMatchToIdentityUrl = (recordUrl, identityUrl) => {
3116
- let parsedRecordUrl;
3117
- let parsedIdentityUrl;
3118
- try {
3119
- parsedRecordUrl = new URL(recordUrl);
3120
- parsedIdentityUrl = new URL(identityUrl);
3121
- }
3122
- catch (error) {
3123
- return false;
3124
- }
3125
- if (parsedRecordUrl.origin !== parsedIdentityUrl.origin) {
3126
- return false;
3127
- }
3128
- const recordPath = removeTrailingSlash(parsedRecordUrl.pathname);
3129
- const identityPath = removeTrailingSlash(parsedIdentityUrl.pathname);
3130
- if (recordPath !== identityPath) {
3131
- return false;
3132
- }
3133
- for (const [key, value] of parsedRecordUrl.searchParams) {
3134
- if (parsedIdentityUrl.searchParams.get(key) !== value) {
3135
- return false;
3136
- }
3137
- }
3138
- if (parsedRecordUrl.hash && parsedRecordUrl.hash !== parsedIdentityUrl.hash) {
3139
- return false;
3140
- }
3141
- return true;
3142
- };
3143
- const checkIfFDC3Channel = (object) => {
3144
- if (!object || typeof object !== "object" || Array.isArray(object)) {
3145
- return false;
3146
- }
3147
- if (!channelTypes.includes(object?.type)) {
3148
- return false;
3149
- }
3150
- return defaultChannelsProps.every((prop) => Object.keys(object).includes(prop));
3151
- };
3152
- const checkIfFDC3Context = (object) => {
3153
- if (!object || typeof object !== "object" || Array.isArray(object)) {
3154
- return false;
3155
- }
3156
- return "type" in object && typeof object.type === "string";
3157
- };
3158
-
3159
3704
  class IOController {
3160
3705
  _io;
3161
3706
  _initializationStarted = false;
@@ -3231,9 +3776,10 @@
3231
3776
  }
3232
3777
  }
3233
3778
 
3234
- const { nonEmptyStringDecoder } = decoders.common;
3779
+ const { nonEmptyStringDecoder, nullable } = decoders.common;
3235
3780
  const addIntentListenerRequestPayloadDecoder = object$1({
3236
- intent: nonEmptyStringDecoder
3781
+ intent: nonEmptyStringDecoder,
3782
+ contextTypes: optional$1(contextTypesStringArrayDecoder)
3237
3783
  });
3238
3784
  const addIntentListenerRequestDecoder = object$1({
3239
3785
  type: constant$1("addIntentListenerRequest"),
@@ -3274,7 +3820,8 @@
3274
3820
  const intentResultRequestPayloadDecoder = object$1({
3275
3821
  intentEventUuid: nonEmptyStringDecoder,
3276
3822
  intentResult: intentResultDecoder,
3277
- raiseIntentRequestUuid: nonEmptyStringDecoder
3823
+ raiseIntentRequestUuid: nonEmptyStringDecoder,
3824
+ metadata: optionalAppProvidableContextMetadataDecoder
3278
3825
  });
3279
3826
  const intentResultRequestDecoder = object$1({
3280
3827
  type: constant$1("intentResultRequest"),
@@ -3283,7 +3830,9 @@
3283
3830
  });
3284
3831
  const raiseIntentForContextRequestPayloadDecoder = object$1({
3285
3832
  context: contextDecoder,
3286
- app: optional$1(appIdentifierDecoder)
3833
+ app: optional$1(appIdentifierDecoder),
3834
+ metadata: optionalAppProvidableContextMetadataDecoder,
3835
+ newInstance: optional$1(nullable(boolean$1())).map((value) => value ?? undefined)
3287
3836
  });
3288
3837
  const raiseIntentForContextRequestDecoder = object$1({
3289
3838
  type: constant$1("raiseIntentForContextRequest"),
@@ -3293,7 +3842,9 @@
3293
3842
  const raiseIntentRequestPayloadDecoder = object$1({
3294
3843
  intent: nonEmptyStringDecoder,
3295
3844
  context: contextDecoder,
3296
- app: optional$1(appIdentifierDecoder)
3845
+ app: optional$1(appIdentifierDecoder),
3846
+ metadata: optionalAppProvidableContextMetadataDecoder,
3847
+ newInstance: optional$1(nullable(boolean$1())).map((value) => value ?? undefined)
3297
3848
  });
3298
3849
  const raiseIntentRequestDecoder = object$1({
3299
3850
  type: constant$1("raiseIntentRequest"),
@@ -3377,6 +3928,7 @@
3377
3928
  const raiseIntentResultResponsePayloadDecoder = object$1({
3378
3929
  error: optional$1(responsePayloadErrorDecoder),
3379
3930
  intentResult: optional$1(intentResultDecoder),
3931
+ resultMetadata: optional$1(contextMetadataDecoder)
3380
3932
  });
3381
3933
  const raiseIntentResultResponseDecoder = object$1({
3382
3934
  type: constant$1("raiseIntentResultResponse"),
@@ -3388,6 +3940,7 @@
3388
3940
  sendBridgeMessage;
3389
3941
  addPrivateChannel;
3390
3942
  isIntentResolverEnabled;
3943
+ myAppMetadata;
3391
3944
  logger;
3392
3945
  listenersCollection = {};
3393
3946
  intentResolutionsCollection = {};
@@ -3399,14 +3952,15 @@
3399
3952
  findIntentsByContextRequest: { requestType: "findIntentsByContextRequest", requestDecoder: findIntentsByContextRequestDecoder, responseType: "findIntentsByContextResponse", responseDecoder: findIntentsByContextResponseDecoder, execute: this.handleFindIntentsByContextRequest.bind(this) },
3400
3953
  intentListenerUnsubscribeRequest: { requestType: "intentListenerUnsubscribeRequest", requestDecoder: intentListenerUnsubscribeRequestDecoder, responseType: "intentListenerUnsubscribeResponse", responseDecoder: intentListenerUnsubscribeResponseDecoder, execute: this.handleIntentListenerUnsubscribeRequest.bind(this) },
3401
3954
  intentResultRequest: { requestType: "intentResultRequest", requestDecoder: intentResultRequestDecoder, responseType: "intentResultResponse", responseDecoder: intentResultResponseDecoder, execute: this.handleIntentResultRequest.bind(this) },
3402
- raiseIntentForContextRequest: { requestType: "raiseIntentForContextRequest", requestDecoder: raiseIntentForContextRequestDecoder, responseType: "raiseIntentForContextResponse", responseDecoder: raiseIntentForContextResponseDecoder, execute: this.handleRaiseIntentForContextRequest.bind(this) },
3403
- raiseIntentRequest: { requestType: "raiseIntentRequest", requestDecoder: raiseIntentRequestDecoder, responseType: "raiseIntentResponse", responseDecoder: raiseIntentResponseDecoder, execute: this.handleRaiseIntentRequest.bind(this) },
3404
- raiseIntentResultRequest: { requestType: "raiseIntentResultRequest", requestDecoder: raiseIntentResultRequestDecoder, responseType: "raiseIntentResultResponse", responseDecoder: raiseIntentResultResponseDecoder, execute: this.handleRaiseIntentResultResponse.bind(this) },
3955
+ raiseIntentForContextRequest: { requestType: "raiseIntentForContextRequest", requestDecoder: raiseIntentForContextRequestDecoder, responseType: "raiseIntentForContextResponse", responseDecoder: raiseIntentForContextResponseDecoder, execute: this.handleRaiseIntentForContextRequest.bind(this), postResponse: this.processRaiseIntentResultResponse.bind(this) },
3956
+ raiseIntentRequest: { requestType: "raiseIntentRequest", requestDecoder: raiseIntentRequestDecoder, responseType: "raiseIntentResponse", responseDecoder: raiseIntentResponseDecoder, execute: this.handleRaiseIntentRequest.bind(this), postResponse: this.processRaiseIntentResultResponse.bind(this) },
3957
+ raiseIntentResultRequest: { requestType: "raiseIntentResultRequest", requestDecoder: raiseIntentResultRequestDecoder, responseType: "raiseIntentResultResponse", responseDecoder: raiseIntentResultResponseDecoder, execute: this.handleRaiseIntentResultRequest.bind(this) },
3405
3958
  };
3406
- constructor(sendBridgeMessage, addPrivateChannel, isIntentResolverEnabled, logger) {
3959
+ constructor(sendBridgeMessage, addPrivateChannel, isIntentResolverEnabled, myAppMetadata, logger) {
3407
3960
  this.sendBridgeMessage = sendBridgeMessage;
3408
3961
  this.addPrivateChannel = addPrivateChannel;
3409
3962
  this.isIntentResolverEnabled = isIntentResolverEnabled;
3963
+ this.myAppMetadata = myAppMetadata;
3410
3964
  this.logger = logger;
3411
3965
  }
3412
3966
  async handleControl(request) {
@@ -3441,18 +3995,34 @@
3441
3995
  this.logger?.info(`Returning response: ${JSON.stringify(response)}`);
3442
3996
  return response;
3443
3997
  }
3998
+ async handlePostResponse(request) {
3999
+ const operation = this.operations[request.type];
4000
+ await operation.postResponse?.(request);
4001
+ }
3444
4002
  async handleAddIntentListenerRequest({ meta, payload }) {
3445
- const handler = async (context, metadata) => {
4003
+ const handler = this.createIntentHandler(payload.intent, meta);
4004
+ const listenerUUID = nanoid();
4005
+ try {
4006
+ const listener = await (payload.contextTypes
4007
+ ? window.fdc3?.addIntentListenerWithContext(payload.intent, payload.contextTypes, handler)
4008
+ : window.fdc3?.addIntentListener(payload.intent, handler));
4009
+ this.listenersCollection[listenerUUID] = listener;
4010
+ return { listenerUUID };
4011
+ }
4012
+ catch (error) {
4013
+ return {
4014
+ error: typeof error === "string" ? error : error.message
4015
+ };
4016
+ }
4017
+ }
4018
+ createIntentHandler(intent, meta) {
4019
+ return async (context, metadata) => {
3446
4020
  const eventUuid = nanoid();
3447
4021
  this.logger?.info(`Received intent event with context: ${JSON.stringify(context)} and metadata: ${JSON.stringify(metadata)}`);
3448
4022
  const intentEventPayload = {
3449
- intent: payload.intent,
4023
+ intent,
3450
4024
  context,
3451
- originatingApp: {
3452
- appId: metadata?.source.appId ?? "",
3453
- instanceId: metadata?.source.instanceId,
3454
- desktopAgent: DESKTOP_AGENT_NAME
3455
- },
4025
+ metadata,
3456
4026
  raiseIntentRequestUuid: meta.requestUuid
3457
4027
  };
3458
4028
  this.intentEventPayloadCollection[meta.requestUuid] = intentEventPayload;
@@ -3472,24 +4042,22 @@
3472
4042
  delete this.intentHandlerResultPromiseCollection[eventUuid];
3473
4043
  return resultToReturn;
3474
4044
  };
3475
- const listenerUUID = nanoid();
3476
- const listener = await window.fdc3?.addIntentListener(payload.intent, handler);
3477
- this.listenersCollection[listenerUUID] = listener;
3478
- return { listenerUUID };
3479
4045
  }
3480
- getIntentResultToReturn(result) {
3481
- this.logger?.info(`Processing received intent result: ${JSON.stringify(result)}`);
3482
- if (!result || (typeof result === "object" && !Object.keys(result).length)) {
4046
+ getIntentResultToReturn({ intentResult, metadata }) {
4047
+ this.logger?.info(`Processing received intent result: ${JSON.stringify(intentResult)}`);
4048
+ if (!intentResult || (typeof intentResult === "object" && !Object.keys(intentResult).length)) {
3483
4049
  return undefined;
3484
4050
  }
3485
- if (result.context) {
3486
- return result.context;
4051
+ if (intentResult.context) {
4052
+ return metadata
4053
+ ? { context: intentResult.context, metadata: metadata }
4054
+ : intentResult.context;
3487
4055
  }
3488
- if (result.channel) {
4056
+ if (intentResult.channel) {
3489
4057
  return {
3490
- id: result.channel.id,
3491
- type: result.channel.type,
3492
- displayMetadata: result.channel.displayMetadata,
4058
+ id: intentResult.channel.id,
4059
+ type: intentResult.channel.type,
4060
+ displayMetadata: intentResult.channel.displayMetadata,
3493
4061
  broadcast: async () => { },
3494
4062
  addContextListener: async () => { },
3495
4063
  getCurrentContext: async () => { }
@@ -3509,121 +4077,234 @@
3509
4077
  if (!listener) {
3510
4078
  return { error: "MalformedMessage", reason: `Cannot find listener with id ${payload.listenerUUID}` };
3511
4079
  }
3512
- listener.unsubscribe();
4080
+ await listener.unsubscribe();
3513
4081
  delete this.listenersCollection[payload.listenerUUID];
3514
4082
  return {};
3515
4083
  }
3516
- async handleIntentResultRequest({ payload }) {
4084
+ handleIntentResultRequest({ payload }) {
3517
4085
  this.logger?.info(`Received intent result request with payload: ${JSON.stringify(payload)}`);
3518
4086
  const intentEventUuid = payload.intentEventUuid;
3519
4087
  const intentEventResultPromise = this.intentHandlerResultPromiseCollection[intentEventUuid];
3520
4088
  if (!intentEventResultPromise) {
3521
4089
  this.logger?.error(`No intent handler result promise found for eventUuid: ${intentEventUuid}`);
3522
- return { error: "MalformedMessage" };
4090
+ return Promise.resolve({ error: "MalformedMessage" });
3523
4091
  }
3524
4092
  this.logger?.info(`Resolving intent handler result promise for eventUuid: ${intentEventUuid} with result: ${JSON.stringify(payload.intentResult)}`);
3525
- intentEventResultPromise.resolve(payload.intentResult);
3526
- return {};
4093
+ intentEventResultPromise.resolve({ intentResult: payload.intentResult, metadata: payload.metadata });
4094
+ return Promise.resolve({});
3527
4095
  }
3528
4096
  async handleRaiseIntentForContextRequest({ meta, payload, type }) {
3529
- if (this.isIntentResolverEnabled && !payload.app) {
4097
+ if (this.isIntentResolverEnabled) {
3530
4098
  return this.handleRaiseIntentForContextRequestWithResolver({ payload, meta, type });
3531
4099
  }
3532
- const intentResolution = await window.fdc3?.raiseIntentForContext(payload.context, payload.app);
4100
+ return this.raiseIntentForContext({ payload, meta });
4101
+ }
4102
+ async raiseIntentForContext({ payload, meta }) {
4103
+ const newInstance = payload.newInstance ?? undefined;
4104
+ const enrichedMetadata = buildEnrichedMetadata(payload.metadata, this.myAppMetadata);
4105
+ const intentResolution = await window.fdc3?.raiseIntentForContext(payload.context, payload.app, newInstance, enrichedMetadata);
3533
4106
  if (!intentResolution) {
3534
4107
  return { error: "IntentDeliveryFailed" };
3535
4108
  }
3536
4109
  this.logger?.info(`Saving intent resolution for requestUuid: ${meta.requestUuid}`);
3537
4110
  this.intentResolutionsCollection[meta.requestUuid] = intentResolution;
3538
4111
  const intentResolutionToReturn = { source: intentResolution.source, intent: intentResolution.intent };
3539
- this.processRaiseIntentResultResponseAsync({
3540
- type: "raiseIntentForContextRequest",
3541
- payload,
3542
- meta
3543
- });
3544
4112
  return { intentResolution: intentResolutionToReturn };
3545
4113
  }
3546
- async handleRaiseIntentForContextRequestWithResolver({ payload, meta, type }) {
3547
- const appIntents = await window.fdc3?.findIntentsByContext(payload.context);
3548
- if (!appIntents || !appIntents.length) {
3549
- return { error: "NoAppsFound" };
4114
+ async handleRaiseIntentForContextRequestWithResolver({ payload, meta }) {
4115
+ const appIntents = await window.fdc3?.findIntentsByContext(payload.context)
4116
+ .catch((error) => {
4117
+ if (error?.message === ResolveError.NoAppsFound) {
4118
+ return [];
4119
+ }
4120
+ throw error;
4121
+ });
4122
+ const eligibleAppIntents = (appIntents ?? [])
4123
+ .map((appIntent) => ({
4124
+ ...appIntent,
4125
+ apps: appIntent.apps.filter((app) => {
4126
+ if (payload.app && app.appId !== payload.app.appId) {
4127
+ return false;
4128
+ }
4129
+ if (payload.app?.instanceId) {
4130
+ return app.instanceId === payload.app.instanceId;
4131
+ }
4132
+ if (payload.newInstance === true) {
4133
+ return !app.instanceId;
4134
+ }
4135
+ if (payload.newInstance === false) {
4136
+ return !!app.instanceId;
4137
+ }
4138
+ return true;
4139
+ })
4140
+ }))
4141
+ .filter((appIntent) => appIntent.apps.length);
4142
+ const allAvailableHandlers = eligibleAppIntents.flatMap((intent) => intent.apps);
4143
+ if (!allAvailableHandlers.length) {
4144
+ if (payload.app?.instanceId) {
4145
+ return this.raiseIntentForContext({ payload: { ...payload, newInstance: undefined }, meta });
4146
+ }
4147
+ const error = payload.newInstance === false ? "TargetInstanceUnavailable" : "NoAppsFound";
4148
+ if (payload.app) {
4149
+ return this.getUnavailableAppTargetError(payload.app, error);
4150
+ }
4151
+ return { error };
3550
4152
  }
3551
- const allAvailableHandlers = appIntents.map((intent) => intent.apps).flat();
3552
- if (allAvailableHandlers.length > 1) {
4153
+ if (eligibleAppIntents.length > 1 || allAvailableHandlers.length > 1) {
3553
4154
  this.logger?.info(`Multiple apps found for context type '${payload.context.type}'. Requesting user to select app using the Intent Resolver UI. Apps: ${JSON.stringify(allAvailableHandlers)}`);
3554
- return { appIntents };
4155
+ return { appIntents: eligibleAppIntents };
3555
4156
  }
3556
- const updatedPayload = { ...payload, app: allAvailableHandlers[0] };
3557
- this.logger?.info(`Only one app found to handle context type '${payload.context.type}'. Proceeding to raise intent to app: '${updatedPayload.app}'`);
3558
- return this.handleRaiseIntentForContextRequest({ type, meta, payload: updatedPayload });
4157
+ const updatedPayload = {
4158
+ ...payload,
4159
+ app: allAvailableHandlers[0],
4160
+ newInstance: payload.app?.instanceId ? undefined : payload.newInstance
4161
+ };
4162
+ this.logger?.info(`Only one app found to handle context type '${payload.context.type}'. Proceeding to raise intent to app: '${JSON.stringify(updatedPayload.app)}'`);
4163
+ return this.raiseIntentForContext({ payload: updatedPayload, meta });
3559
4164
  }
3560
4165
  async handleRaiseIntentRequest({ payload, meta, type }) {
3561
- if (this.isIntentResolverEnabled && !payload.app) {
4166
+ if (payload.app?.instanceId) {
4167
+ const updatedPayload = { ...payload, newInstance: undefined };
4168
+ return this.raiseIntent({ payload: updatedPayload, meta, type });
4169
+ }
4170
+ if (this.isIntentResolverEnabled) {
3562
4171
  return this.handleRaiseIntentRequestWithResolver({ payload, meta, type });
3563
4172
  }
3564
- const intentResolution = await window.fdc3?.raiseIntent(payload.intent, payload.context, payload.app);
4173
+ return this.raiseIntent({ payload, meta, type });
4174
+ }
4175
+ async raiseIntent({ payload, meta }) {
4176
+ const newInstance = payload.newInstance ?? undefined;
4177
+ const metadata = buildEnrichedMetadata(payload.metadata, this.myAppMetadata);
4178
+ const intentResolution = await window.fdc3?.raiseIntent(payload.intent, payload.context, payload.app, newInstance, metadata);
3565
4179
  if (!intentResolution) {
3566
4180
  return { error: "IntentDeliveryFailed" };
3567
4181
  }
3568
4182
  this.logger?.info(`Saving intent resolution for requestUuid: ${meta.requestUuid}`);
3569
4183
  this.intentResolutionsCollection[meta.requestUuid] = intentResolution;
3570
4184
  const intentResolutionToReturn = { source: intentResolution.source, intent: intentResolution.intent };
3571
- this.processRaiseIntentResultResponseAsync({
3572
- type: "raiseIntentRequest",
3573
- payload,
3574
- meta
3575
- });
3576
4185
  return { intentResolution: intentResolutionToReturn };
3577
4186
  }
3578
4187
  async handleRaiseIntentRequestWithResolver({ payload, meta, type }) {
3579
- const appIntent = await window.fdc3?.findIntent(payload.intent, payload.context);
3580
- if (!appIntent || !appIntent.apps.length) {
4188
+ const appIntent = await window.fdc3?.findIntent(payload.intent, payload.context)
4189
+ .catch((error) => {
4190
+ if (error?.message === ResolveError.NoAppsFound) {
4191
+ return undefined;
4192
+ }
4193
+ throw error;
4194
+ });
4195
+ if (!appIntent?.apps?.length) {
4196
+ if (payload.app) {
4197
+ return this.getUnavailableAppTargetError(payload.app);
4198
+ }
3581
4199
  return { error: "NoAppsFound" };
3582
4200
  }
4201
+ if (payload.app) {
4202
+ return this.handleRaiseIntentRequestWithResolverAndAppTarget({ payload, meta, type }, appIntent);
4203
+ }
4204
+ if (typeof payload.newInstance === "boolean") {
4205
+ return this.handleRaiseIntentRequestWithResolverAndNewInstance({ payload, meta, type }, appIntent);
4206
+ }
3583
4207
  if (appIntent.apps.length > 1) {
3584
4208
  this.logger?.info(`Multiple apps found for intent '${payload.intent}'. Requesting user to select app using the Intent Resolver UI. Apps: ${JSON.stringify(appIntent.apps)}`);
3585
4209
  return { appIntent };
3586
4210
  }
3587
4211
  const updatedPayload = { ...payload, app: appIntent.apps[0] };
3588
- this.logger?.info(`Only one app found to handle intent. Proceeding to raise intent to app: '${updatedPayload.app}'`);
3589
- return this.handleRaiseIntentRequest({ type, meta, payload: updatedPayload });
4212
+ this.logger?.info(`Only one app found to handle intent. Proceeding to raise intent to app: '${JSON.stringify(updatedPayload.app)}'`);
4213
+ return this.raiseIntent({ type, meta, payload: updatedPayload });
3590
4214
  }
3591
- async handleRaiseIntentResultResponse({ payload, meta }) {
3592
- this.logger?.info(`handleRaiseIntentResultResponse called with payload: ${JSON.stringify(payload)} and meta: ${JSON.stringify(meta)}`);
3593
- const intentResolution = await this.intentResolutionsCollection[meta.requestUuid];
4215
+ async handleRaiseIntentRequestWithResolverAndAppTarget({ payload, type, meta }, appIntent) {
4216
+ if (!payload.app) {
4217
+ return { error: "TargetAppUnavailable" };
4218
+ }
4219
+ const targetApps = appIntent.apps.filter((app) => app.appId === payload.app?.appId);
4220
+ if (!targetApps.length) {
4221
+ return this.getUnavailableAppTargetError(payload.app);
4222
+ }
4223
+ if (typeof payload.newInstance !== "boolean") {
4224
+ return this.raiseIntent({ type, meta, payload });
4225
+ }
4226
+ const instanceHandlers = targetApps.filter((app) => app.instanceId);
4227
+ const appHandlers = targetApps.filter((app) => !app.instanceId);
4228
+ if (payload.newInstance === true) {
4229
+ if (!appHandlers.length) {
4230
+ return { error: "TargetAppUnavailable" };
4231
+ }
4232
+ return this.raiseIntent({ type, meta, payload: { ...payload, app: payload.app } });
4233
+ }
4234
+ if (payload.newInstance === false && !instanceHandlers.length) {
4235
+ return { error: "TargetInstanceUnavailable" };
4236
+ }
4237
+ if (instanceHandlers.length === 1) {
4238
+ const updatedPayload = {
4239
+ ...payload,
4240
+ app: instanceHandlers[0],
4241
+ newInstance: false
4242
+ };
4243
+ this.logger?.info(`Only one running instance found for target app '${payload.app?.appId}'. Proceeding to raise intent to app: '${JSON.stringify(updatedPayload.app)}'`);
4244
+ return this.raiseIntent({ type, meta, payload: updatedPayload });
4245
+ }
4246
+ this.logger?.info(`Multiple running instances found for target app '${payload.app?.appId}'. Requesting user to select app using the Intent Resolver UI. Apps: ${JSON.stringify(instanceHandlers)}`);
4247
+ return { appIntent: { intent: appIntent.intent, apps: instanceHandlers } };
4248
+ }
4249
+ async getUnavailableAppTargetError(app, knownAppError = "NoAppsFound") {
4250
+ const appMetadata = await window.fdc3?.getAppMetadata?.(app);
4251
+ return { error: appMetadata ? knownAppError : "TargetAppUnavailable" };
4252
+ }
4253
+ async handleRaiseIntentRequestWithResolverAndNewInstance({ payload, type, meta }, appIntent) {
4254
+ const { newInstance } = payload;
4255
+ const eligibleApps = appIntent.apps.filter((app) => newInstance ? !app.instanceId : !!app.instanceId);
4256
+ if (!eligibleApps.length) {
4257
+ return { error: "TargetInstanceUnavailable" };
4258
+ }
4259
+ if (eligibleApps.length === 1) {
4260
+ const updatedPayload = { ...payload, app: eligibleApps[0] };
4261
+ this.logger?.info(`Only one eligible app found to handle intent. Proceeding to raise intent to app: '${JSON.stringify(updatedPayload.app)}'`);
4262
+ return this.raiseIntent({ type, meta, payload: updatedPayload });
4263
+ }
4264
+ this.logger?.info(`Multiple eligible apps found for intent '${payload.intent}'. Requesting user to select app using the Intent Resolver UI. Apps: ${JSON.stringify(eligibleApps)}`);
4265
+ return { appIntent: { intent: appIntent.intent, apps: eligibleApps } };
4266
+ }
4267
+ async handleRaiseIntentResultRequest({ payload, meta }) {
4268
+ this.logger?.info(`handleRaiseIntentResultRequest called with payload: ${JSON.stringify(payload)} and meta: ${JSON.stringify(meta)}`);
4269
+ const intentResolution = this.intentResolutionsCollection[meta.requestUuid];
3594
4270
  if (!intentResolution) {
3595
4271
  this.logger?.info(`Did not find intent resolution for requestUuid: ${meta.requestUuid}`);
3596
4272
  return { error: "IntentDeliveryFailed" };
3597
4273
  }
3598
4274
  this.logger?.info(`Found intent resolution for requestUuid: ${meta.requestUuid}. Retrieving result...`);
3599
4275
  const result = await intentResolution.getResult();
3600
- this.logger?.info(`Received intent result: ${JSON.stringify(result)}`);
4276
+ const resultMetadata = await intentResolution.getResultMetadata();
4277
+ const responseMetadata = resultMetadata;
4278
+ this.logger?.info(`Received intent result: ${JSON.stringify(result)} with metadata: ${JSON.stringify(resultMetadata)}`);
3601
4279
  if (!result) {
3602
4280
  const intentStr = payload.intent ? "intent '" + payload.intent + "'" : "";
3603
4281
  const contextStr = payload.context ? "context type '" + payload.context.type + "'" : "";
3604
4282
  this.logger?.info(`Intent result is void for ${intentStr}, ${contextStr} and requestUuid: ${meta.requestUuid}`);
3605
- return { intentResult: undefined };
4283
+ return { intentResult: undefined, resultMetadata: responseMetadata };
3606
4284
  }
3607
- const intentResult = this.extractRaiseIntentResult(result);
3608
- this.logger?.info(`Extracted intent result: ${JSON.stringify(intentResult)}`);
4285
+ const intentResult = this.extractRaiseIntentResult(result, responseMetadata);
3609
4286
  return intentResult;
3610
4287
  }
3611
- extractRaiseIntentResult(receivedResult) {
4288
+ extractRaiseIntentResult(receivedResult, resultMetadata) {
3612
4289
  if (!receivedResult) {
3613
- return { intentResult: undefined };
4290
+ return { intentResult: undefined, resultMetadata };
3614
4291
  }
3615
4292
  const isChannel = checkIfFDC3Channel(receivedResult);
3616
4293
  if (isChannel) {
3617
4294
  this.checkSetPrivateChanel(receivedResult);
3618
- return { intentResult: { channel: JSON.parse(JSON.stringify(receivedResult)) } };
4295
+ return { intentResult: { channel: JSON.parse(JSON.stringify(receivedResult)) }, resultMetadata };
3619
4296
  }
3620
4297
  const isContext = checkIfFDC3Context(receivedResult);
3621
4298
  if (isContext) {
3622
- return { intentResult: { context: receivedResult } };
4299
+ return { intentResult: { context: receivedResult }, resultMetadata };
3623
4300
  }
3624
4301
  if (receivedResult.error) {
3625
4302
  return { error: receivedResult.error };
3626
4303
  }
4304
+ const isContextWithMetadata = checkIfFDC3ContextWithMetadata(receivedResult);
4305
+ if (isContextWithMetadata) {
4306
+ return { intentResult: { context: receivedResult.context }, resultMetadata: receivedResult.metadata };
4307
+ }
3627
4308
  return { error: "IntentDeliveryFailed" };
3628
4309
  }
3629
4310
  checkSetPrivateChanel(channel) {
@@ -3633,8 +4314,10 @@
3633
4314
  }
3634
4315
  this.addPrivateChannel(channel);
3635
4316
  }
3636
- async processRaiseIntentResultResponseAsync({ payload, meta }) {
3637
- this.logger?.warn("Processing raise intent result response asynchronously with payload: " + JSON.stringify(payload));
4317
+ async processRaiseIntentResultResponse({ payload, meta }) {
4318
+ if (!this.intentResolutionsCollection[meta.requestUuid]) {
4319
+ return;
4320
+ }
3638
4321
  const syntheticRequest = {
3639
4322
  type: "raiseIntentResultRequest",
3640
4323
  meta: {
@@ -3670,6 +4353,7 @@
3670
4353
  _intentsController;
3671
4354
  _applicationsController;
3672
4355
  _uiConfig;
4356
+ _myAppMetadata;
3673
4357
  resetState() {
3674
4358
  this._bridgeController = undefined;
3675
4359
  this._ioController = undefined;
@@ -3678,6 +4362,13 @@
3678
4362
  this._intentsController = undefined;
3679
4363
  this._applicationsController = undefined;
3680
4364
  this._uiConfig = undefined;
4365
+ this._myAppMetadata = undefined;
4366
+ }
4367
+ get myAppMetadata() {
4368
+ return this._myAppMetadata;
4369
+ }
4370
+ set myAppMetadata(value) {
4371
+ this._myAppMetadata = value;
3681
4372
  }
3682
4373
  get uiConfig() {
3683
4374
  return this._uiConfig;
@@ -3708,25 +4399,25 @@
3708
4399
  }
3709
4400
  get channelsController() {
3710
4401
  if (!this._channelsController) {
3711
- this._channelsController = new ChannelsController(this.bridgeController.sendMessage.bind(this.bridgeController), this.ioController.getLogger("channels.controller"));
4402
+ this._channelsController = new ChannelsController(this.bridgeController.sendMessage.bind(this.bridgeController), this.myAppMetadata, this.ioController.getLogger("channels.controller"));
3712
4403
  }
3713
4404
  return this._channelsController;
3714
4405
  }
3715
4406
  get intentsController() {
3716
4407
  if (!this._intentsController) {
3717
- this._intentsController = new IntentsController(this.bridgeController.sendMessage.bind(this.bridgeController), this.channelsController.addPrivateChannel.bind(this.channelsController), this.uiConfig.isIntentResolverEnabled, this.ioController.getLogger("intents.controller"));
4408
+ this._intentsController = new IntentsController(this.bridgeController.sendMessage.bind(this.bridgeController), this.channelsController.addPrivateChannel.bind(this.channelsController), this.uiConfig.isIntentResolverEnabled, this.myAppMetadata, this.ioController.getLogger("intents.controller"));
3718
4409
  }
3719
4410
  return this._intentsController;
3720
4411
  }
3721
4412
  get applicationsController() {
3722
4413
  if (!this._applicationsController) {
3723
- this._applicationsController = new ApplicationsController(this.ioController.getLogger("applications.controller"));
4414
+ this._applicationsController = new ApplicationsController(this.myAppMetadata, this.ioController.getLogger("applications.controller"));
3724
4415
  }
3725
4416
  return this._applicationsController;
3726
4417
  }
3727
4418
  }
3728
4419
 
3729
- var version = "1.5.0";
4420
+ var version = "2.0.0";
3730
4421
 
3731
4422
  window.fdc3WebBridgeInfo = {
3732
4423
  version