@interopio/fdc3 2.1.2 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/fdc3.umd.js CHANGED
@@ -19,6 +19,203 @@
19
19
  PERFORMANCE OF THIS SOFTWARE.
20
20
  ***************************************************************************** */
21
21
 
22
+ function __rest$2(s, e) {
23
+ var t = {};
24
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
25
+ t[p] = s[p];
26
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
27
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
28
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
29
+ t[p[i]] = s[p[i]];
30
+ }
31
+ return t;
32
+ }
33
+
34
+ function __awaiter(thisArg, _arguments, P, generator) {
35
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
36
+ return new (P || (P = Promise))(function (resolve, reject) {
37
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
38
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
39
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
40
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
41
+ });
42
+ }
43
+
44
+ let nanoid = (size = 21) =>
45
+ crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
46
+ byte &= 63;
47
+ if (byte < 36) {
48
+ id += byte.toString(36);
49
+ } else if (byte < 62) {
50
+ id += (byte - 26).toString(36).toUpperCase();
51
+ } else if (byte > 62) {
52
+ id += '-';
53
+ } else {
54
+ id += '_';
55
+ }
56
+ return id
57
+ }, '');
58
+
59
+ const isValidNonEmptyObject = (obj) => {
60
+ return typeof obj === "object" && !Array.isArray(obj) && Object.keys(obj).length !== 0;
61
+ };
62
+ const AsyncListener = (actualUnsub) => {
63
+ return {
64
+ unsubscribe() {
65
+ if (!actualUnsub) {
66
+ console.error("Failed to unsubscribe!");
67
+ return;
68
+ }
69
+ if (typeof actualUnsub === "function") {
70
+ actualUnsub();
71
+ }
72
+ else {
73
+ actualUnsub.then((unsubFunc) => unsubFunc()).catch(console.error);
74
+ }
75
+ }
76
+ };
77
+ };
78
+ const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => {
79
+ return new Promise((resolve, reject) => {
80
+ const timeout = setTimeout(() => {
81
+ const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`;
82
+ reject(message);
83
+ }, timeoutMilliseconds);
84
+ promise()
85
+ .then((result) => {
86
+ clearTimeout(timeout);
87
+ resolve(result);
88
+ })
89
+ .catch((error) => {
90
+ clearTimeout(timeout);
91
+ reject(error);
92
+ });
93
+ });
94
+ };
95
+ const generateCommandId = () => {
96
+ return nanoid();
97
+ };
98
+
99
+ const connectBrowserAppProps = ["name", "title", "version", "customProperties", "icon", "caption", "type"];
100
+ const fdc3v2AppProps = ["appId", "name", "type", "details", "version", "title", "tooltip", "lang", "description", "categories", "icons", "screenshots", "contactEmail", "moreInfo", "publisher", "customConfig", "hostManifests", "interop", "localizedVersions"];
101
+
102
+ /**
103
+ * Wraps values in an `Ok` type.
104
+ *
105
+ * Example: `ok(5) // => {ok: true, result: 5}`
106
+ */
107
+ var ok$1 = function (result) { return ({ ok: true, result: result }); };
108
+ /**
109
+ * Wraps errors in an `Err` type.
110
+ *
111
+ * Example: `err('on fire') // => {ok: false, error: 'on fire'}`
112
+ */
113
+ var err$1 = function (error) { return ({ ok: false, error: error }); };
114
+ /**
115
+ * Create a `Promise` that either resolves with the result of `Ok` or rejects
116
+ * with the error of `Err`.
117
+ */
118
+ var asPromise$1 = function (r) {
119
+ return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error);
120
+ };
121
+ /**
122
+ * Unwraps a `Result` and returns either the result of an `Ok`, or
123
+ * `defaultValue`.
124
+ *
125
+ * Example:
126
+ * ```
127
+ * Result.withDefault(5, number().run(json))
128
+ * ```
129
+ *
130
+ * It would be nice if `Decoder` had an instance method that mirrored this
131
+ * function. Such a method would look something like this:
132
+ * ```
133
+ * class Decoder<A> {
134
+ * runWithDefault = (defaultValue: A, json: any): A =>
135
+ * Result.withDefault(defaultValue, this.run(json));
136
+ * }
137
+ *
138
+ * number().runWithDefault(5, json)
139
+ * ```
140
+ * Unfortunately, the type of `defaultValue: A` on the method causes issues
141
+ * with type inference on the `object` decoder in some situations. While these
142
+ * inference issues can be solved by providing the optional type argument for
143
+ * `object`s, the extra trouble and confusion doesn't seem worth it.
144
+ */
145
+ var withDefault$1 = function (defaultValue, r) {
146
+ return r.ok === true ? r.result : defaultValue;
147
+ };
148
+ /**
149
+ * Return the successful result, or throw an error.
150
+ */
151
+ var withException$1 = function (r) {
152
+ if (r.ok === true) {
153
+ return r.result;
154
+ }
155
+ else {
156
+ throw r.error;
157
+ }
158
+ };
159
+ /**
160
+ * Apply `f` to the result of an `Ok`, or pass the error through.
161
+ */
162
+ var map$1 = function (f, r) {
163
+ return r.ok === true ? ok$1(f(r.result)) : r;
164
+ };
165
+ /**
166
+ * Apply `f` to the result of two `Ok`s, or pass an error through. If both
167
+ * `Result`s are errors then the first one is returned.
168
+ */
169
+ var map2$1 = function (f, ar, br) {
170
+ return ar.ok === false ? ar :
171
+ br.ok === false ? br :
172
+ ok$1(f(ar.result, br.result));
173
+ };
174
+ /**
175
+ * Apply `f` to the error of an `Err`, or pass the success through.
176
+ */
177
+ var mapError$1 = function (f, r) {
178
+ return r.ok === true ? r : err$1(f(r.error));
179
+ };
180
+ /**
181
+ * Chain together a sequence of computations that may fail, similar to a
182
+ * `Promise`. If the first computation fails then the error will propagate
183
+ * through. If it succeeds, then `f` will be applied to the value, returning a
184
+ * new `Result`.
185
+ */
186
+ var andThen$1 = function (f, r) {
187
+ return r.ok === true ? f(r.result) : r;
188
+ };
189
+
190
+ /*! *****************************************************************************
191
+ Copyright (c) Microsoft Corporation.
192
+
193
+ Permission to use, copy, modify, and/or distribute this software for any
194
+ purpose with or without fee is hereby granted.
195
+
196
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
197
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
198
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
199
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
200
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
201
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
202
+ PERFORMANCE OF THIS SOFTWARE.
203
+ ***************************************************************************** */
204
+ /* global Reflect, Promise */
205
+
206
+
207
+
208
+ var __assign$1 = function() {
209
+ __assign$1 = Object.assign || function __assign(t) {
210
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
211
+ s = arguments[i];
212
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
213
+ }
214
+ return t;
215
+ };
216
+ return __assign$1.apply(this, arguments);
217
+ };
218
+
22
219
  function __rest$1(s, e) {
23
220
  var t = {};
24
221
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
@@ -31,73 +228,1034 @@
31
228
  return t;
32
229
  }
33
230
 
34
- function __awaiter(thisArg, _arguments, P, generator) {
35
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
36
- return new (P || (P = Promise))(function (resolve, reject) {
37
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
38
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
39
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
40
- step((generator = generator.apply(thisArg, _arguments || [])).next());
41
- });
231
+ function isEqual$1(a, b) {
232
+ if (a === b) {
233
+ return true;
234
+ }
235
+ if (a === null && b === null) {
236
+ return true;
237
+ }
238
+ if (typeof (a) !== typeof (b)) {
239
+ return false;
240
+ }
241
+ if (typeof (a) === 'object') {
242
+ // Array
243
+ if (Array.isArray(a)) {
244
+ if (!Array.isArray(b)) {
245
+ return false;
246
+ }
247
+ if (a.length !== b.length) {
248
+ return false;
249
+ }
250
+ for (var i = 0; i < a.length; i++) {
251
+ if (!isEqual$1(a[i], b[i])) {
252
+ return false;
253
+ }
254
+ }
255
+ return true;
256
+ }
257
+ // Hash table
258
+ var keys = Object.keys(a);
259
+ if (keys.length !== Object.keys(b).length) {
260
+ return false;
261
+ }
262
+ for (var i = 0; i < keys.length; i++) {
263
+ if (!b.hasOwnProperty(keys[i])) {
264
+ return false;
265
+ }
266
+ if (!isEqual$1(a[keys[i]], b[keys[i]])) {
267
+ return false;
268
+ }
269
+ }
270
+ return true;
271
+ }
272
+ }
273
+ /*
274
+ * Helpers
275
+ */
276
+ var isJsonArray$1 = function (json) { return Array.isArray(json); };
277
+ var isJsonObject$1 = function (json) {
278
+ return typeof json === 'object' && json !== null && !isJsonArray$1(json);
279
+ };
280
+ var typeString$1 = function (json) {
281
+ switch (typeof json) {
282
+ case 'string':
283
+ return 'a string';
284
+ case 'number':
285
+ return 'a number';
286
+ case 'boolean':
287
+ return 'a boolean';
288
+ case 'undefined':
289
+ return 'undefined';
290
+ case 'object':
291
+ if (json instanceof Array) {
292
+ return 'an array';
293
+ }
294
+ else if (json === null) {
295
+ return 'null';
296
+ }
297
+ else {
298
+ return 'an object';
299
+ }
300
+ default:
301
+ return JSON.stringify(json);
302
+ }
303
+ };
304
+ var expectedGot$1 = function (expected, got) {
305
+ return "expected " + expected + ", got " + typeString$1(got);
306
+ };
307
+ var printPath$1 = function (paths) {
308
+ return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join('');
309
+ };
310
+ var prependAt$1 = function (newAt, _a) {
311
+ var at = _a.at, rest = __rest$1(_a, ["at"]);
312
+ return (__assign$1({ at: newAt + (at || '') }, rest));
313
+ };
314
+ /**
315
+ * Decoders transform json objects with unknown structure into known and
316
+ * verified forms. You can create objects of type `Decoder<A>` with either the
317
+ * primitive decoder functions, such as `boolean()` and `string()`, or by
318
+ * applying higher-order decoders to the primitives, such as `array(boolean())`
319
+ * or `dict(string())`.
320
+ *
321
+ * Each of the decoder functions are available both as a static method on
322
+ * `Decoder` and as a function alias -- for example the string decoder is
323
+ * defined at `Decoder.string()`, but is also aliased to `string()`. Using the
324
+ * function aliases exported with the library is recommended.
325
+ *
326
+ * `Decoder` exposes a number of 'run' methods, which all decode json in the
327
+ * same way, but communicate success and failure in different ways. The `map`
328
+ * and `andThen` methods modify decoders without having to call a 'run' method.
329
+ *
330
+ * Alternatively, the main decoder `run()` method returns an object of type
331
+ * `Result<A, DecoderError>`. This library provides a number of helper
332
+ * functions for dealing with the `Result` type, so you can do all the same
333
+ * things with a `Result` as with the decoder methods.
334
+ */
335
+ var Decoder$1 = /** @class */ (function () {
336
+ /**
337
+ * The Decoder class constructor is kept private to separate the internal
338
+ * `decode` function from the external `run` function. The distinction
339
+ * between the two functions is that `decode` returns a
340
+ * `Partial<DecoderError>` on failure, which contains an unfinished error
341
+ * report. When `run` is called on a decoder, the relevant series of `decode`
342
+ * calls is made, and then on failure the resulting `Partial<DecoderError>`
343
+ * is turned into a `DecoderError` by filling in the missing information.
344
+ *
345
+ * While hiding the constructor may seem restrictive, leveraging the
346
+ * provided decoder combinators and helper functions such as
347
+ * `andThen` and `map` should be enough to build specialized decoders as
348
+ * needed.
349
+ */
350
+ function Decoder(decode) {
351
+ var _this = this;
352
+ this.decode = decode;
353
+ /**
354
+ * Run the decoder and return a `Result` with either the decoded value or a
355
+ * `DecoderError` containing the json input, the location of the error, and
356
+ * the error message.
357
+ *
358
+ * Examples:
359
+ * ```
360
+ * number().run(12)
361
+ * // => {ok: true, result: 12}
362
+ *
363
+ * string().run(9001)
364
+ * // =>
365
+ * // {
366
+ * // ok: false,
367
+ * // error: {
368
+ * // kind: 'DecoderError',
369
+ * // input: 9001,
370
+ * // at: 'input',
371
+ * // message: 'expected a string, got 9001'
372
+ * // }
373
+ * // }
374
+ * ```
375
+ */
376
+ this.run = function (json) {
377
+ return mapError$1(function (error) { return ({
378
+ kind: 'DecoderError',
379
+ input: json,
380
+ at: 'input' + (error.at || ''),
381
+ message: error.message || ''
382
+ }); }, _this.decode(json));
383
+ };
384
+ /**
385
+ * Run the decoder as a `Promise`.
386
+ */
387
+ this.runPromise = function (json) { return asPromise$1(_this.run(json)); };
388
+ /**
389
+ * Run the decoder and return the value on success, or throw an exception
390
+ * with a formatted error string.
391
+ */
392
+ this.runWithException = function (json) { return withException$1(_this.run(json)); };
393
+ /**
394
+ * Construct a new decoder that applies a transformation to the decoded
395
+ * result. If the decoder succeeds then `f` will be applied to the value. If
396
+ * it fails the error will propagated through.
397
+ *
398
+ * Example:
399
+ * ```
400
+ * number().map(x => x * 5).run(10)
401
+ * // => {ok: true, result: 50}
402
+ * ```
403
+ */
404
+ this.map = function (f) {
405
+ return new Decoder(function (json) { return map$1(f, _this.decode(json)); });
406
+ };
407
+ /**
408
+ * Chain together a sequence of decoders. The first decoder will run, and
409
+ * then the function will determine what decoder to run second. If the result
410
+ * of the first decoder succeeds then `f` will be applied to the decoded
411
+ * value. If it fails the error will propagate through.
412
+ *
413
+ * This is a very powerful method -- it can act as both the `map` and `where`
414
+ * methods, can improve error messages for edge cases, and can be used to
415
+ * make a decoder for custom types.
416
+ *
417
+ * Example of adding an error message:
418
+ * ```
419
+ * const versionDecoder = valueAt(['version'], number());
420
+ * const infoDecoder3 = object({a: boolean()});
421
+ *
422
+ * const decoder = versionDecoder.andThen(version => {
423
+ * switch (version) {
424
+ * case 3:
425
+ * return infoDecoder3;
426
+ * default:
427
+ * return fail(`Unable to decode info, version ${version} is not supported.`);
428
+ * }
429
+ * });
430
+ *
431
+ * decoder.run({version: 3, a: true})
432
+ * // => {ok: true, result: {a: true}}
433
+ *
434
+ * decoder.run({version: 5, x: 'abc'})
435
+ * // =>
436
+ * // {
437
+ * // ok: false,
438
+ * // error: {... message: 'Unable to decode info, version 5 is not supported.'}
439
+ * // }
440
+ * ```
441
+ *
442
+ * Example of decoding a custom type:
443
+ * ```
444
+ * // nominal type for arrays with a length of at least one
445
+ * type NonEmptyArray<T> = T[] & { __nonEmptyArrayBrand__: void };
446
+ *
447
+ * const nonEmptyArrayDecoder = <T>(values: Decoder<T>): Decoder<NonEmptyArray<T>> =>
448
+ * array(values).andThen(arr =>
449
+ * arr.length > 0
450
+ * ? succeed(createNonEmptyArray(arr))
451
+ * : fail(`expected a non-empty array, got an empty array`)
452
+ * );
453
+ * ```
454
+ */
455
+ this.andThen = function (f) {
456
+ return new Decoder(function (json) {
457
+ return andThen$1(function (value) { return f(value).decode(json); }, _this.decode(json));
458
+ });
459
+ };
460
+ /**
461
+ * Add constraints to a decoder _without_ changing the resulting type. The
462
+ * `test` argument is a predicate function which returns true for valid
463
+ * inputs. When `test` fails on an input, the decoder fails with the given
464
+ * `errorMessage`.
465
+ *
466
+ * ```
467
+ * const chars = (length: number): Decoder<string> =>
468
+ * string().where(
469
+ * (s: string) => s.length === length,
470
+ * `expected a string of length ${length}`
471
+ * );
472
+ *
473
+ * chars(5).run('12345')
474
+ * // => {ok: true, result: '12345'}
475
+ *
476
+ * chars(2).run('HELLO')
477
+ * // => {ok: false, error: {... message: 'expected a string of length 2'}}
478
+ *
479
+ * chars(12).run(true)
480
+ * // => {ok: false, error: {... message: 'expected a string, got a boolean'}}
481
+ * ```
482
+ */
483
+ this.where = function (test, errorMessage) {
484
+ return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); });
485
+ };
486
+ }
487
+ /**
488
+ * Decoder primitive that validates strings, and fails on all other input.
489
+ */
490
+ Decoder.string = function () {
491
+ return new Decoder(function (json) {
492
+ return typeof json === 'string'
493
+ ? ok$1(json)
494
+ : err$1({ message: expectedGot$1('a string', json) });
495
+ });
496
+ };
497
+ /**
498
+ * Decoder primitive that validates numbers, and fails on all other input.
499
+ */
500
+ Decoder.number = function () {
501
+ return new Decoder(function (json) {
502
+ return typeof json === 'number'
503
+ ? ok$1(json)
504
+ : err$1({ message: expectedGot$1('a number', json) });
505
+ });
506
+ };
507
+ /**
508
+ * Decoder primitive that validates booleans, and fails on all other input.
509
+ */
510
+ Decoder.boolean = function () {
511
+ return new Decoder(function (json) {
512
+ return typeof json === 'boolean'
513
+ ? ok$1(json)
514
+ : err$1({ message: expectedGot$1('a boolean', json) });
515
+ });
516
+ };
517
+ Decoder.constant = function (value) {
518
+ return new Decoder(function (json) {
519
+ return isEqual$1(json, value)
520
+ ? ok$1(value)
521
+ : err$1({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) });
522
+ });
523
+ };
524
+ Decoder.object = function (decoders) {
525
+ return new Decoder(function (json) {
526
+ if (isJsonObject$1(json) && decoders) {
527
+ var obj = {};
528
+ for (var key in decoders) {
529
+ if (decoders.hasOwnProperty(key)) {
530
+ var r = decoders[key].decode(json[key]);
531
+ if (r.ok === true) {
532
+ // tslint:disable-next-line:strict-type-predicates
533
+ if (r.result !== undefined) {
534
+ obj[key] = r.result;
535
+ }
536
+ }
537
+ else if (json[key] === undefined) {
538
+ return err$1({ message: "the key '" + key + "' is required but was not present" });
539
+ }
540
+ else {
541
+ return err$1(prependAt$1("." + key, r.error));
542
+ }
543
+ }
544
+ }
545
+ return ok$1(obj);
546
+ }
547
+ else if (isJsonObject$1(json)) {
548
+ return ok$1(json);
549
+ }
550
+ else {
551
+ return err$1({ message: expectedGot$1('an object', json) });
552
+ }
553
+ });
554
+ };
555
+ Decoder.array = function (decoder) {
556
+ return new Decoder(function (json) {
557
+ if (isJsonArray$1(json) && decoder) {
558
+ var decodeValue_1 = function (v, i) {
559
+ return mapError$1(function (err$$1) { return prependAt$1("[" + i + "]", err$$1); }, decoder.decode(v));
560
+ };
561
+ return json.reduce(function (acc, v, i) {
562
+ return map2$1(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i));
563
+ }, ok$1([]));
564
+ }
565
+ else if (isJsonArray$1(json)) {
566
+ return ok$1(json);
567
+ }
568
+ else {
569
+ return err$1({ message: expectedGot$1('an array', json) });
570
+ }
571
+ });
572
+ };
573
+ Decoder.tuple = function (decoders) {
574
+ return new Decoder(function (json) {
575
+ if (isJsonArray$1(json)) {
576
+ if (json.length !== decoders.length) {
577
+ return err$1({
578
+ message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length
579
+ });
580
+ }
581
+ var result = [];
582
+ for (var i = 0; i < decoders.length; i++) {
583
+ var nth = decoders[i].decode(json[i]);
584
+ if (nth.ok) {
585
+ result[i] = nth.result;
586
+ }
587
+ else {
588
+ return err$1(prependAt$1("[" + i + "]", nth.error));
589
+ }
590
+ }
591
+ return ok$1(result);
592
+ }
593
+ else {
594
+ return err$1({ message: expectedGot$1("a tuple of length " + decoders.length, json) });
595
+ }
596
+ });
597
+ };
598
+ Decoder.union = function (ad, bd) {
599
+ var decoders = [];
600
+ for (var _i = 2; _i < arguments.length; _i++) {
601
+ decoders[_i - 2] = arguments[_i];
602
+ }
603
+ return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders));
604
+ };
605
+ Decoder.intersection = function (ad, bd) {
606
+ var ds = [];
607
+ for (var _i = 2; _i < arguments.length; _i++) {
608
+ ds[_i - 2] = arguments[_i];
609
+ }
610
+ return new Decoder(function (json) {
611
+ return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$1(Object.assign, acc, decoder.decode(json)); }, ok$1({}));
612
+ });
613
+ };
614
+ /**
615
+ * Escape hatch to bypass validation. Always succeeds and types the result as
616
+ * `any`. Useful for defining decoders incrementally, particularly for
617
+ * complex objects.
618
+ *
619
+ * Example:
620
+ * ```
621
+ * interface User {
622
+ * name: string;
623
+ * complexUserData: ComplexType;
624
+ * }
625
+ *
626
+ * const userDecoder: Decoder<User> = object({
627
+ * name: string(),
628
+ * complexUserData: anyJson()
629
+ * });
630
+ * ```
631
+ */
632
+ Decoder.anyJson = function () { return new Decoder(function (json) { return ok$1(json); }); };
633
+ /**
634
+ * Decoder identity function which always succeeds and types the result as
635
+ * `unknown`.
636
+ */
637
+ Decoder.unknownJson = function () {
638
+ return new Decoder(function (json) { return ok$1(json); });
639
+ };
640
+ /**
641
+ * Decoder for json objects where the keys are unknown strings, but the values
642
+ * should all be of the same type.
643
+ *
644
+ * Example:
645
+ * ```
646
+ * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37});
647
+ * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}}
648
+ * ```
649
+ */
650
+ Decoder.dict = function (decoder) {
651
+ return new Decoder(function (json) {
652
+ if (isJsonObject$1(json)) {
653
+ var obj = {};
654
+ for (var key in json) {
655
+ if (json.hasOwnProperty(key)) {
656
+ var r = decoder.decode(json[key]);
657
+ if (r.ok === true) {
658
+ obj[key] = r.result;
659
+ }
660
+ else {
661
+ return err$1(prependAt$1("." + key, r.error));
662
+ }
663
+ }
664
+ }
665
+ return ok$1(obj);
666
+ }
667
+ else {
668
+ return err$1({ message: expectedGot$1('an object', json) });
669
+ }
670
+ });
671
+ };
672
+ /**
673
+ * Decoder for values that may be `undefined`. This is primarily helpful for
674
+ * decoding interfaces with optional fields.
675
+ *
676
+ * Example:
677
+ * ```
678
+ * interface User {
679
+ * id: number;
680
+ * isOwner?: boolean;
681
+ * }
682
+ *
683
+ * const decoder: Decoder<User> = object({
684
+ * id: number(),
685
+ * isOwner: optional(boolean())
686
+ * });
687
+ * ```
688
+ */
689
+ Decoder.optional = function (decoder) {
690
+ return new Decoder(function (json) { return (json === undefined || json === null ? ok$1(undefined) : decoder.decode(json)); });
691
+ };
692
+ /**
693
+ * Decoder that attempts to run each decoder in `decoders` and either succeeds
694
+ * with the first successful decoder, or fails after all decoders have failed.
695
+ *
696
+ * Note that `oneOf` expects the decoders to all have the same return type,
697
+ * while `union` creates a decoder for the union type of all the input
698
+ * decoders.
699
+ *
700
+ * Examples:
701
+ * ```
702
+ * oneOf(string(), number().map(String))
703
+ * oneOf(constant('start'), constant('stop'), succeed('unknown'))
704
+ * ```
705
+ */
706
+ Decoder.oneOf = function () {
707
+ var decoders = [];
708
+ for (var _i = 0; _i < arguments.length; _i++) {
709
+ decoders[_i] = arguments[_i];
710
+ }
711
+ return new Decoder(function (json) {
712
+ var errors = [];
713
+ for (var i = 0; i < decoders.length; i++) {
714
+ var r = decoders[i].decode(json);
715
+ if (r.ok === true) {
716
+ return r;
717
+ }
718
+ else {
719
+ errors[i] = r.error;
720
+ }
721
+ }
722
+ var errorsList = errors
723
+ .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; })
724
+ .join('", "');
725
+ return err$1({
726
+ message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]"
727
+ });
728
+ });
729
+ };
730
+ /**
731
+ * Decoder that always succeeds with either the decoded value, or a fallback
732
+ * default value.
733
+ */
734
+ Decoder.withDefault = function (defaultValue, decoder) {
735
+ return new Decoder(function (json) {
736
+ return ok$1(withDefault$1(defaultValue, decoder.decode(json)));
737
+ });
738
+ };
739
+ /**
740
+ * Decoder that pulls a specific field out of a json structure, instead of
741
+ * decoding and returning the full structure. The `paths` array describes the
742
+ * object keys and array indices to traverse, so that values can be pulled out
743
+ * of a nested structure.
744
+ *
745
+ * Example:
746
+ * ```
747
+ * const decoder = valueAt(['a', 'b', 0], string());
748
+ *
749
+ * decoder.run({a: {b: ['surprise!']}})
750
+ * // => {ok: true, result: 'surprise!'}
751
+ *
752
+ * decoder.run({a: {x: 'cats'}})
753
+ * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}}
754
+ * ```
755
+ *
756
+ * Note that the `decoder` is ran on the value found at the last key in the
757
+ * path, even if the last key is not found. This allows the `optional`
758
+ * decoder to succeed when appropriate.
759
+ * ```
760
+ * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string()));
761
+ *
762
+ * optionalDecoder.run({a: {b: {c: 'surprise!'}}})
763
+ * // => {ok: true, result: 'surprise!'}
764
+ *
765
+ * optionalDecoder.run({a: {b: 'cats'}})
766
+ * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'}
767
+ *
768
+ * optionalDecoder.run({a: {b: {z: 1}}})
769
+ * // => {ok: true, result: undefined}
770
+ * ```
771
+ */
772
+ Decoder.valueAt = function (paths, decoder) {
773
+ return new Decoder(function (json) {
774
+ var jsonAtPath = json;
775
+ for (var i = 0; i < paths.length; i++) {
776
+ if (jsonAtPath === undefined) {
777
+ return err$1({
778
+ at: printPath$1(paths.slice(0, i + 1)),
779
+ message: 'path does not exist'
780
+ });
781
+ }
782
+ else if (typeof paths[i] === 'string' && !isJsonObject$1(jsonAtPath)) {
783
+ return err$1({
784
+ at: printPath$1(paths.slice(0, i + 1)),
785
+ message: expectedGot$1('an object', jsonAtPath)
786
+ });
787
+ }
788
+ else if (typeof paths[i] === 'number' && !isJsonArray$1(jsonAtPath)) {
789
+ return err$1({
790
+ at: printPath$1(paths.slice(0, i + 1)),
791
+ message: expectedGot$1('an array', jsonAtPath)
792
+ });
793
+ }
794
+ else {
795
+ jsonAtPath = jsonAtPath[paths[i]];
796
+ }
797
+ }
798
+ return mapError$1(function (error) {
799
+ return jsonAtPath === undefined
800
+ ? { at: printPath$1(paths), message: 'path does not exist' }
801
+ : prependAt$1(printPath$1(paths), error);
802
+ }, decoder.decode(jsonAtPath));
803
+ });
804
+ };
805
+ /**
806
+ * Decoder that ignores the input json and always succeeds with `fixedValue`.
807
+ */
808
+ Decoder.succeed = function (fixedValue) {
809
+ return new Decoder(function (json) { return ok$1(fixedValue); });
810
+ };
811
+ /**
812
+ * Decoder that ignores the input json and always fails with `errorMessage`.
813
+ */
814
+ Decoder.fail = function (errorMessage) {
815
+ return new Decoder(function (json) { return err$1({ message: errorMessage }); });
816
+ };
817
+ /**
818
+ * Decoder that allows for validating recursive data structures. Unlike with
819
+ * functions, decoders assigned to variables can't reference themselves
820
+ * before they are fully defined. We can avoid prematurely referencing the
821
+ * decoder by wrapping it in a function that won't be called until use, at
822
+ * which point the decoder has been defined.
823
+ *
824
+ * Example:
825
+ * ```
826
+ * interface Comment {
827
+ * msg: string;
828
+ * replies: Comment[];
829
+ * }
830
+ *
831
+ * const decoder: Decoder<Comment> = object({
832
+ * msg: string(),
833
+ * replies: lazy(() => array(decoder))
834
+ * });
835
+ * ```
836
+ */
837
+ Decoder.lazy = function (mkDecoder) {
838
+ return new Decoder(function (json) { return mkDecoder().decode(json); });
839
+ };
840
+ return Decoder;
841
+ }());
842
+
843
+ /* tslint:disable:variable-name */
844
+ /** See `Decoder.string` */
845
+ var string$1 = Decoder$1.string;
846
+ /** See `Decoder.number` */
847
+ var number$1 = Decoder$1.number;
848
+ /** See `Decoder.boolean` */
849
+ var boolean = Decoder$1.boolean;
850
+ /** See `Decoder.anyJson` */
851
+ var anyJson$1 = Decoder$1.anyJson;
852
+ /** See `Decoder.unknownJson` */
853
+ Decoder$1.unknownJson;
854
+ /** See `Decoder.constant` */
855
+ var constant$1 = Decoder$1.constant;
856
+ /** See `Decoder.object` */
857
+ var object$1 = Decoder$1.object;
858
+ /** See `Decoder.array` */
859
+ var array$1 = Decoder$1.array;
860
+ /** See `Decoder.tuple` */
861
+ Decoder$1.tuple;
862
+ /** See `Decoder.dict` */
863
+ var dict = Decoder$1.dict;
864
+ /** See `Decoder.optional` */
865
+ var optional$1 = Decoder$1.optional;
866
+ /** See `Decoder.oneOf` */
867
+ var oneOf$1 = Decoder$1.oneOf;
868
+ /** See `Decoder.union` */
869
+ Decoder$1.union;
870
+ /** See `Decoder.intersection` */
871
+ Decoder$1.intersection;
872
+ /** See `Decoder.withDefault` */
873
+ Decoder$1.withDefault;
874
+ /** See `Decoder.valueAt` */
875
+ Decoder$1.valueAt;
876
+ /** See `Decoder.succeed` */
877
+ Decoder$1.succeed;
878
+ /** See `Decoder.fail` */
879
+ Decoder$1.fail;
880
+ /** See `Decoder.lazy` */
881
+ Decoder$1.lazy;
882
+
883
+ const nonEmptyStringDecoder$1 = string$1().where((s) => s.length > 0, "Expected a non-empty string");
884
+ const nonNegativeNumberDecoder = number$1().where((num) => num >= 0, "Expected a non-negative number");
885
+
886
+ const intentDefinitionDecoder = object$1({
887
+ name: nonEmptyStringDecoder$1,
888
+ displayName: optional$1(string$1()),
889
+ contexts: optional$1(array$1(string$1())),
890
+ customConfig: optional$1(object$1())
891
+ });
892
+ const v2TypeDecoder = oneOf$1(constant$1("web"), constant$1("native"), constant$1("citrix"), constant$1("onlineNative"), constant$1("other"));
893
+ const v2DetailsDecoder = object$1({
894
+ url: nonEmptyStringDecoder$1
895
+ });
896
+ const v2IconDecoder = object$1({
897
+ src: nonEmptyStringDecoder$1,
898
+ size: optional$1(nonEmptyStringDecoder$1),
899
+ type: optional$1(nonEmptyStringDecoder$1)
900
+ });
901
+ const v2ScreenshotDecoder = object$1({
902
+ src: nonEmptyStringDecoder$1,
903
+ size: optional$1(nonEmptyStringDecoder$1),
904
+ type: optional$1(nonEmptyStringDecoder$1),
905
+ label: optional$1(nonEmptyStringDecoder$1)
906
+ });
907
+ const v2ListensForIntentDecoder = object$1({
908
+ contexts: array$1(nonEmptyStringDecoder$1),
909
+ displayName: optional$1(nonEmptyStringDecoder$1),
910
+ resultType: optional$1(nonEmptyStringDecoder$1),
911
+ customConfig: optional$1(anyJson$1())
912
+ });
913
+ const v2IntentsDecoder = object$1({
914
+ listensFor: optional$1(dict(v2ListensForIntentDecoder)),
915
+ raises: optional$1(dict(array$1(nonEmptyStringDecoder$1)))
916
+ });
917
+ const v2UserChannelDecoder = object$1({
918
+ broadcasts: optional$1(array$1(nonEmptyStringDecoder$1)),
919
+ listensFor: optional$1(array$1(nonEmptyStringDecoder$1))
920
+ });
921
+ const v2AppChannelDecoder = object$1({
922
+ name: nonEmptyStringDecoder$1,
923
+ description: optional$1(nonEmptyStringDecoder$1),
924
+ broadcasts: optional$1(array$1(nonEmptyStringDecoder$1)),
925
+ listensFor: optional$1(array$1(nonEmptyStringDecoder$1))
926
+ });
927
+ const v2InteropDecoder = object$1({
928
+ intents: optional$1(v2IntentsDecoder),
929
+ userChannels: optional$1(v2UserChannelDecoder),
930
+ appChannels: optional$1(array$1(v2AppChannelDecoder))
931
+ });
932
+ const glue42ApplicationDetailsDecoder = object$1({
933
+ url: nonEmptyStringDecoder$1,
934
+ top: optional$1(number$1()),
935
+ left: optional$1(number$1()),
936
+ width: optional$1(nonNegativeNumberDecoder),
937
+ height: optional$1(nonNegativeNumberDecoder)
938
+ });
939
+ const glue42HostManifestsBrowserDecoder = object$1({
940
+ name: optional$1(nonEmptyStringDecoder$1),
941
+ type: optional$1(nonEmptyStringDecoder$1.where((s) => s === "window", "Expected a value of window")),
942
+ title: optional$1(nonEmptyStringDecoder$1),
943
+ version: optional$1(nonEmptyStringDecoder$1),
944
+ customProperties: optional$1(anyJson$1()),
945
+ icon: optional$1(string$1()),
946
+ caption: optional$1(string$1()),
947
+ details: optional$1(glue42ApplicationDetailsDecoder),
948
+ intents: optional$1(array$1(intentDefinitionDecoder)),
949
+ hidden: optional$1(boolean())
950
+ });
951
+ const hostManifestsBrowserDecoder = oneOf$1(object$1({
952
+ "Glue42": oneOf$1(glue42HostManifestsBrowserDecoder, anyJson$1())
953
+ }), anyJson$1());
954
+ const v1DefinitionDecoder = object$1({
955
+ name: nonEmptyStringDecoder$1,
956
+ appId: nonEmptyStringDecoder$1,
957
+ title: optional$1(nonEmptyStringDecoder$1),
958
+ version: optional$1(nonEmptyStringDecoder$1),
959
+ manifest: nonEmptyStringDecoder$1,
960
+ manifestType: nonEmptyStringDecoder$1,
961
+ tooltip: optional$1(nonEmptyStringDecoder$1),
962
+ description: optional$1(nonEmptyStringDecoder$1),
963
+ contactEmail: optional$1(nonEmptyStringDecoder$1),
964
+ supportEmail: optional$1(nonEmptyStringDecoder$1),
965
+ publisher: optional$1(nonEmptyStringDecoder$1),
966
+ images: optional$1(array$1(object$1({ url: optional$1(nonEmptyStringDecoder$1) }))),
967
+ icons: optional$1(array$1(object$1({ icon: optional$1(nonEmptyStringDecoder$1) }))),
968
+ customConfig: anyJson$1(),
969
+ intents: optional$1(array$1(intentDefinitionDecoder))
970
+ });
971
+ const v2LocalizedDefinitionDecoder = object$1({
972
+ appId: optional$1(nonEmptyStringDecoder$1),
973
+ name: optional$1(nonEmptyStringDecoder$1),
974
+ details: optional$1(v2DetailsDecoder),
975
+ version: optional$1(nonEmptyStringDecoder$1),
976
+ title: optional$1(nonEmptyStringDecoder$1),
977
+ tooltip: optional$1(nonEmptyStringDecoder$1),
978
+ lang: optional$1(nonEmptyStringDecoder$1),
979
+ description: optional$1(nonEmptyStringDecoder$1),
980
+ categories: optional$1(array$1(nonEmptyStringDecoder$1)),
981
+ icons: optional$1(array$1(v2IconDecoder)),
982
+ screenshots: optional$1(array$1(v2ScreenshotDecoder)),
983
+ contactEmail: optional$1(nonEmptyStringDecoder$1),
984
+ supportEmail: optional$1(nonEmptyStringDecoder$1),
985
+ moreInfo: optional$1(nonEmptyStringDecoder$1),
986
+ publisher: optional$1(nonEmptyStringDecoder$1),
987
+ customConfig: optional$1(array$1(anyJson$1())),
988
+ hostManifests: optional$1(hostManifestsBrowserDecoder),
989
+ interop: optional$1(v2InteropDecoder)
990
+ });
991
+ const v2DefinitionDecoder = object$1({
992
+ appId: nonEmptyStringDecoder$1,
993
+ name: nonEmptyStringDecoder$1,
994
+ type: v2TypeDecoder,
995
+ details: v2DetailsDecoder,
996
+ version: optional$1(nonEmptyStringDecoder$1),
997
+ title: optional$1(nonEmptyStringDecoder$1),
998
+ tooltip: optional$1(nonEmptyStringDecoder$1),
999
+ lang: optional$1(nonEmptyStringDecoder$1),
1000
+ description: optional$1(nonEmptyStringDecoder$1),
1001
+ categories: optional$1(array$1(nonEmptyStringDecoder$1)),
1002
+ icons: optional$1(array$1(v2IconDecoder)),
1003
+ screenshots: optional$1(array$1(v2ScreenshotDecoder)),
1004
+ contactEmail: optional$1(nonEmptyStringDecoder$1),
1005
+ supportEmail: optional$1(nonEmptyStringDecoder$1),
1006
+ moreInfo: optional$1(nonEmptyStringDecoder$1),
1007
+ publisher: optional$1(nonEmptyStringDecoder$1),
1008
+ customConfig: optional$1(array$1(anyJson$1())),
1009
+ hostManifests: optional$1(hostManifestsBrowserDecoder),
1010
+ interop: optional$1(v2InteropDecoder),
1011
+ localizedVersions: optional$1(dict(v2LocalizedDefinitionDecoder))
1012
+ });
1013
+ const allDefinitionsDecoder = oneOf$1(v1DefinitionDecoder, v2DefinitionDecoder);
1014
+
1015
+ const parseDecoderErrorToStringMessage = (error) => {
1016
+ return `${error.kind} at ${error.at}: ${JSON.stringify(error.input)}. Reason - ${error.message}`;
1017
+ };
1018
+
1019
+ class FDC3Service {
1020
+ constructor() {
1021
+ this.fdc3ToDesktopDefinitionType = {
1022
+ web: "window",
1023
+ native: "exe",
1024
+ citrix: "citrix",
1025
+ onlineNative: "clickonce",
1026
+ other: "window"
1027
+ };
1028
+ }
1029
+ toApi() {
1030
+ return {
1031
+ isFdc3Definition: this.isFdc3Definition.bind(this),
1032
+ parseToBrowserBaseAppData: this.parseToBrowserBaseAppData.bind(this),
1033
+ parseToDesktopAppConfig: this.parseToDesktopAppConfig.bind(this)
1034
+ };
1035
+ }
1036
+ isFdc3Definition(definition) {
1037
+ const decodeRes = allDefinitionsDecoder.run(definition);
1038
+ if (!decodeRes.ok) {
1039
+ return { isFdc3: false, reason: parseDecoderErrorToStringMessage(decodeRes.error) };
1040
+ }
1041
+ if (definition.appId && definition.details) {
1042
+ return { isFdc3: true, version: "2.0" };
1043
+ }
1044
+ if (definition.manifest) {
1045
+ return { isFdc3: true, version: "1.2" };
1046
+ }
1047
+ return { isFdc3: false, reason: "The passed definition is not FDC3" };
1048
+ }
1049
+ parseToBrowserBaseAppData(definition) {
1050
+ var _a;
1051
+ const { isFdc3, version } = this.isFdc3Definition(definition);
1052
+ if (!isFdc3) {
1053
+ throw new Error("The passed definition is not FDC3");
1054
+ }
1055
+ const decodeRes = allDefinitionsDecoder.run(definition);
1056
+ if (!decodeRes.ok) {
1057
+ throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`);
1058
+ }
1059
+ const userProperties = this.getUserPropertiesFromDefinition(definition, version);
1060
+ const createOptions = { url: this.getUrl(definition, version) };
1061
+ let baseApplicationData = {
1062
+ name: definition.appId,
1063
+ type: "window",
1064
+ createOptions,
1065
+ userProperties: Object.assign(Object.assign({}, userProperties), { intents: version === "1.2"
1066
+ ? userProperties.intents
1067
+ : this.getIntentsFromV2AppDefinition(definition), details: createOptions }),
1068
+ title: definition.title,
1069
+ version: definition.version,
1070
+ icon: this.getIconFromDefinition(definition, version),
1071
+ caption: definition.description,
1072
+ fdc3: version === "2.0" ? Object.assign(Object.assign({}, definition), { definitionVersion: "2.0" }) : undefined,
1073
+ };
1074
+ if ((_a = definition.hostManifests) === null || _a === void 0 ? void 0 : _a["Glue42"]) {
1075
+ const decodeRes = glue42HostManifestsBrowserDecoder.run(definition.hostManifests["Glue42"]);
1076
+ if (!decodeRes.ok) {
1077
+ throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`);
1078
+ }
1079
+ if (!Object.keys(decodeRes.result).length) {
1080
+ throw new Error("Invalid 'hostManifests['Glue42]' key");
1081
+ }
1082
+ baseApplicationData = this.mergeBaseAppDataWithGlueManifest(baseApplicationData, decodeRes.result);
1083
+ }
1084
+ return baseApplicationData;
1085
+ }
1086
+ parseToDesktopAppConfig(definition) {
1087
+ var _a, _b, _c;
1088
+ const { isFdc3, version } = this.isFdc3Definition(definition);
1089
+ if (!isFdc3) {
1090
+ throw new Error("The passed definition is not FDC3");
1091
+ }
1092
+ const decodeRes = allDefinitionsDecoder.run(definition);
1093
+ if (!decodeRes.ok) {
1094
+ throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`);
1095
+ }
1096
+ if (version === "1.2") {
1097
+ const fdc3v1Definition = definition;
1098
+ return {
1099
+ name: fdc3v1Definition.appId,
1100
+ type: "window",
1101
+ details: {
1102
+ url: this.getUrl(definition, version)
1103
+ },
1104
+ version: fdc3v1Definition.version,
1105
+ title: fdc3v1Definition.title,
1106
+ tooltip: fdc3v1Definition.tooltip,
1107
+ caption: fdc3v1Definition.description,
1108
+ icon: (_a = fdc3v1Definition.icons) === null || _a === void 0 ? void 0 : _a[0].icon,
1109
+ intents: fdc3v1Definition.intents,
1110
+ customProperties: {
1111
+ manifestType: fdc3v1Definition.manifestType,
1112
+ images: fdc3v1Definition.images,
1113
+ contactEmail: fdc3v1Definition.contactEmail,
1114
+ supportEmail: fdc3v1Definition.supportEmail,
1115
+ publisher: fdc3v1Definition.publisher,
1116
+ icons: fdc3v1Definition.icons,
1117
+ customConfig: fdc3v1Definition.customConfig
1118
+ }
1119
+ };
1120
+ }
1121
+ const fdc3v2Definition = definition;
1122
+ let desktopDefinition = {
1123
+ name: fdc3v2Definition.appId,
1124
+ type: this.fdc3ToDesktopDefinitionType[fdc3v2Definition.type],
1125
+ details: fdc3v2Definition.details,
1126
+ version: fdc3v2Definition.version,
1127
+ title: fdc3v2Definition.title,
1128
+ tooltip: fdc3v2Definition.tooltip,
1129
+ caption: fdc3v2Definition.description,
1130
+ icon: this.getIconFromDefinition(fdc3v2Definition, "2.0"),
1131
+ intents: this.getIntentsFromV2AppDefinition(fdc3v2Definition),
1132
+ fdc3: Object.assign(Object.assign({}, fdc3v2Definition), { definitionVersion: "2.0" })
1133
+ };
1134
+ if ((_b = fdc3v2Definition.hostManifests) === null || _b === void 0 ? void 0 : _b["Glue42"]) {
1135
+ if (typeof fdc3v2Definition.hostManifests["Glue42"] !== "object" || Array.isArray(fdc3v2Definition.hostManifests["Glue42"])) {
1136
+ throw new Error("Invalid 'hostManifests['Glue42]' key");
1137
+ }
1138
+ desktopDefinition = this.mergeDesktopConfigWithGlueManifest(desktopDefinition, (_c = fdc3v2Definition.hostManifests) === null || _c === void 0 ? void 0 : _c["Glue42"]);
1139
+ }
1140
+ return desktopDefinition;
1141
+ }
1142
+ getUserPropertiesFromDefinition(definition, version) {
1143
+ if (version === "1.2") {
1144
+ return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key)));
1145
+ }
1146
+ return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key) && !fdc3v2AppProps.includes(key)));
1147
+ }
1148
+ getUrl(definition, version) {
1149
+ var _a, _b;
1150
+ let url;
1151
+ if (version === "1.2") {
1152
+ const parsedManifest = JSON.parse(definition.manifest);
1153
+ url = ((_a = parsedManifest.details) === null || _a === void 0 ? void 0 : _a.url) || parsedManifest.url;
1154
+ }
1155
+ else {
1156
+ url = (_b = definition.details) === null || _b === void 0 ? void 0 : _b.url;
1157
+ }
1158
+ if (!url || typeof url !== "string") {
1159
+ throw new Error(`Invalid FDC3 ${version} definition. Provide valid 'url' under '${version === "1.2" ? "manifest" : "details"}' key`);
1160
+ }
1161
+ return url;
1162
+ }
1163
+ getIntentsFromV2AppDefinition(definition) {
1164
+ var _a, _b;
1165
+ const fdc3Intents = (_b = (_a = definition.interop) === null || _a === void 0 ? void 0 : _a.intents) === null || _b === void 0 ? void 0 : _b.listensFor;
1166
+ if (!fdc3Intents) {
1167
+ return;
1168
+ }
1169
+ const intents = Object.entries(fdc3Intents).map((fdc3Intent) => {
1170
+ const [intentName, intentData] = fdc3Intent;
1171
+ return Object.assign({ name: intentName }, intentData);
1172
+ });
1173
+ return intents;
1174
+ }
1175
+ getIconFromDefinition(definition, version) {
1176
+ var _a, _b, _c, _d;
1177
+ if (version === "1.2") {
1178
+ return ((_b = (_a = definition.icons) === null || _a === void 0 ? void 0 : _a.find((iconDef) => iconDef.icon)) === null || _b === void 0 ? void 0 : _b.icon) || undefined;
1179
+ }
1180
+ return ((_d = (_c = definition.icons) === null || _c === void 0 ? void 0 : _c.find((iconDef) => iconDef.src)) === null || _d === void 0 ? void 0 : _d.src) || undefined;
1181
+ }
1182
+ mergeBaseAppDataWithGlueManifest(baseAppData, hostManifestDefinition) {
1183
+ let baseApplicationDefinition = baseAppData;
1184
+ if (hostManifestDefinition.details) {
1185
+ const details = Object.assign(Object.assign({}, baseAppData.createOptions), hostManifestDefinition.details);
1186
+ baseApplicationDefinition.createOptions = details;
1187
+ baseApplicationDefinition.userProperties.details = details;
1188
+ }
1189
+ if (Array.isArray(hostManifestDefinition.intents)) {
1190
+ baseApplicationDefinition.userProperties.intents = (baseApplicationDefinition.userProperties.intents || []).concat(hostManifestDefinition.intents);
1191
+ }
1192
+ baseApplicationDefinition = Object.assign(Object.assign({}, baseApplicationDefinition), hostManifestDefinition);
1193
+ delete baseApplicationDefinition.details;
1194
+ delete baseApplicationDefinition.intents;
1195
+ return baseApplicationDefinition;
1196
+ }
1197
+ mergeDesktopConfigWithGlueManifest(config, desktopDefinition) {
1198
+ const appConfig = Object.assign({}, config, desktopDefinition, { details: Object.assign(Object.assign({}, config.details), desktopDefinition.details) });
1199
+ if (Array.isArray(desktopDefinition.intents)) {
1200
+ appConfig.intents = (config.intents || []).concat(desktopDefinition.intents);
1201
+ }
1202
+ return appConfig;
1203
+ }
42
1204
  }
43
1205
 
44
- let nanoid = (size = 21) =>
45
- crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
46
- byte &= 63;
47
- if (byte < 36) {
48
- id += byte.toString(36);
49
- } else if (byte < 62) {
50
- id += (byte - 26).toString(36).toUpperCase();
51
- } else if (byte > 62) {
52
- id += '-';
53
- } else {
54
- id += '_';
1206
+ const decoders$1 = {
1207
+ common: {
1208
+ nonEmptyStringDecoder: nonEmptyStringDecoder$1,
1209
+ nonNegativeNumberDecoder
1210
+ },
1211
+ fdc3: {
1212
+ allDefinitionsDecoder,
1213
+ v1DefinitionDecoder,
1214
+ v2DefinitionDecoder
55
1215
  }
56
- return id
57
- }, '');
1216
+ };
58
1217
 
59
- navigator.userAgent.toLowerCase().includes(" electron/");
60
- navigator.userAgent.toLowerCase().includes(" tick42-glue-desktop/");
61
- const isValidNonEmptyObject = (obj) => {
62
- return typeof obj === "object" && !Array.isArray(obj) && Object.keys(obj).length !== 0;
63
- };
64
- const AsyncListener = (actualUnsub) => {
65
- return {
66
- unsubscribe() {
67
- if (!actualUnsub) {
68
- console.error("Failed to unsubscribe!");
69
- return;
70
- }
71
- if (typeof actualUnsub === "function") {
72
- actualUnsub();
73
- }
74
- else {
75
- actualUnsub.then((unsubFunc) => unsubFunc()).catch(console.error);
76
- }
77
- }
78
- };
79
- };
80
- const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => {
81
- return new Promise((resolve, reject) => {
82
- const timeout = setTimeout(() => {
83
- const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`;
84
- reject(message);
85
- }, timeoutMilliseconds);
86
- promise()
87
- .then((result) => {
88
- clearTimeout(timeout);
89
- resolve(result);
90
- })
91
- .catch((error) => {
92
- clearTimeout(timeout);
93
- reject(error);
94
- });
95
- });
96
- };
97
- const generateCommandId = () => {
98
- return nanoid();
1218
+ var INTENTS_ERRORS;
1219
+ (function (INTENTS_ERRORS) {
1220
+ INTENTS_ERRORS["USER_CANCELLED"] = "User Closed Intents Resolver UI without choosing a handler";
1221
+ INTENTS_ERRORS["CALLER_NOT_DEFINED"] = "Caller Id is not defined";
1222
+ INTENTS_ERRORS["TIMEOUT_HIT"] = "Timeout hit";
1223
+ INTENTS_ERRORS["INTENT_NOT_FOUND"] = "Cannot find Intent";
1224
+ INTENTS_ERRORS["HANDLER_NOT_FOUND"] = "Cannot find Intent Handler";
1225
+ INTENTS_ERRORS["TARGET_INSTANCE_UNAVAILABLE"] = "Cannot start Target Instance";
1226
+ INTENTS_ERRORS["INTENT_DELIVERY_FAILED"] = "Target Instance did not add a listener";
1227
+ INTENTS_ERRORS["RESOLVER_UNAVAILABLE"] = "Intents Resolver UI unavailable";
1228
+ INTENTS_ERRORS["RESOLVER_TIMEOUT"] = "User did not choose a handler";
1229
+ INTENTS_ERRORS["INVALID_RESOLVER_RESPONSE"] = "Intents Resolver UI returned invalid response";
1230
+ INTENTS_ERRORS["INTENT_HANDLER_REJECTION"] = "Intent Handler function processing the raised intent threw an error or rejected the promise it returned";
1231
+ })(INTENTS_ERRORS || (INTENTS_ERRORS = {}));
1232
+
1233
+ let IoC$1 = class IoC {
1234
+ constructor() {
1235
+ this._decoders = decoders$1;
1236
+ this._errors = {
1237
+ intents: INTENTS_ERRORS
1238
+ };
1239
+ }
1240
+ get fdc3() {
1241
+ if (!this._fdc3) {
1242
+ this._fdc3 = new FDC3Service().toApi();
1243
+ }
1244
+ return this._fdc3;
1245
+ }
1246
+ get decoders() {
1247
+ return this._decoders;
1248
+ }
1249
+ get errors() {
1250
+ return this._errors;
1251
+ }
99
1252
  };
100
1253
 
1254
+ const ioc = new IoC$1();
1255
+ ioc.fdc3;
1256
+ ioc.decoders;
1257
+ const errors = ioc.errors;
1258
+
101
1259
  var IntentHandlerResultTypes;
102
1260
  (function (IntentHandlerResultTypes) {
103
1261
  IntentHandlerResultTypes["Context"] = "Context";
@@ -195,7 +1353,8 @@
195
1353
  "fdc3.instrument",
196
1354
  "fdc3.organization"
197
1355
  ]
198
- };
1356
+ };
1357
+ const IO_ERRORS = errors.intents;
199
1358
 
200
1359
  const ioConnectFDC3SystemMethod = "FDC3.Collaborate";
201
1360
  const PrivateChannelPrefix = "___privateFDC3Channel___";
@@ -1110,6 +2269,26 @@
1110
2269
  return this.glue.intents.raise(request);
1111
2270
  });
1112
2271
  }
2272
+ doesFilterHandlersExist() {
2273
+ return !!this.glue.intents.filterHandlers;
2274
+ }
2275
+ filterHandlers(handlerFilter) {
2276
+ return __awaiter(this, void 0, void 0, function* () {
2277
+ if (!this.glue.intents.filterHandlers) {
2278
+ throw new Error("Intents method 'filterHandlers' does not exist");
2279
+ }
2280
+ return this.glue.intents.filterHandlers(handlerFilter);
2281
+ });
2282
+ }
2283
+ doesGetIntentsExist() {
2284
+ return !!this.glue.intents.getIntents;
2285
+ }
2286
+ getIntents(handler) {
2287
+ if (!this.glue.intents.getIntents) {
2288
+ throw new Error("Intents method 'getIntents' does not exist");
2289
+ }
2290
+ return this.glue.intents.getIntents(handler);
2291
+ }
1113
2292
  getMyWindowContext() {
1114
2293
  return __awaiter(this, void 0, void 0, function* () {
1115
2294
  const myWin = this.getMyWindow();
@@ -1213,7 +2392,7 @@
1213
2392
  }
1214
2393
  channelsSubscribe(callback, contextType) {
1215
2394
  const didReplay = { replayed: false };
1216
- return this.glue.channels.subscribe((_, contextData, updaterId) => __awaiter(this, void 0, void 0, function* () {
2395
+ return this.glue.channels.subscribe((_, contextData, updaterId) => {
1217
2396
  if (this.isUpdateFromMe(updaterId) || !contextData || !contextData.latest_fdc3_type) {
1218
2397
  return;
1219
2398
  }
@@ -1222,7 +2401,7 @@
1222
2401
  }
1223
2402
  this.invokePreviouslyBroadcastedData({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
1224
2403
  didReplay.replayed = true;
1225
- }));
2404
+ });
1226
2405
  }
1227
2406
  contextsSubscribe(contextName, callback) {
1228
2407
  const didReplay = { replayed: false };
@@ -1240,7 +2419,8 @@
1240
2419
  return this.glue.interop.servers(methodFilter);
1241
2420
  }
1242
2421
  initSubLogger(name) {
1243
- return this.logger.subLogger(name);
2422
+ var _a;
2423
+ return (_a = this.logger) === null || _a === void 0 ? void 0 : _a.subLogger(name);
1244
2424
  }
1245
2425
  invokePreviouslyBroadcastedData({ callback, contextData, metadata, contextType }) {
1246
2426
  const invokeForType = contextType || this.channelsParser.mapChannelsDelimiterToFDC3Type(contextData.latest_fdc3_type);
@@ -1284,7 +2464,7 @@
1284
2464
  }
1285
2465
  getLatestBroadcastedDataByContextType(contextData, contextType) {
1286
2466
  let foundData;
1287
- Object.entries(contextData.data).find(([key, value]) => {
2467
+ Object.entries(contextData.data).forEach(([key, value]) => {
1288
2468
  if (!this.channelsParser.isFdc3DataKey(key)) {
1289
2469
  return;
1290
2470
  }
@@ -1320,23 +2500,150 @@
1320
2500
  const REQUEST_GLUE_RESPONSE = "requestGlueResponse";
1321
2501
  const FDC3_READY = "fdc3Ready";
1322
2502
 
1323
- class EventDispatcher {
1324
- fireFdc3Ready() {
1325
- const event = new Event(FDC3_READY);
1326
- window.dispatchEvent(event);
1327
- }
1328
- fireNotifyStarted() {
1329
- this.send(NOTIFY_STARTED);
1330
- }
1331
- fireRequestGlue() {
1332
- this.send(REQUEST_GLUE);
1333
- }
1334
- send(eventName, message) {
1335
- const payload = { glue42: { event: eventName, message } };
1336
- const event = new CustomEvent(GLUE42_EVENT_NAME, { detail: payload });
1337
- window.dispatchEvent(event);
1338
- }
1339
- }
2503
+ class EventDispatcher {
2504
+ fireFdc3Ready() {
2505
+ const event = new Event(FDC3_READY);
2506
+ window.dispatchEvent(event);
2507
+ }
2508
+ fireNotifyStarted() {
2509
+ this.send(NOTIFY_STARTED);
2510
+ }
2511
+ fireRequestGlue() {
2512
+ this.send(REQUEST_GLUE);
2513
+ }
2514
+ send(eventName, message) {
2515
+ const payload = { glue42: { event: eventName, message } };
2516
+ const event = new CustomEvent(GLUE42_EVENT_NAME, { detail: payload });
2517
+ window.dispatchEvent(event);
2518
+ }
2519
+ }
2520
+
2521
+ // To parse this data:
2522
+
2523
+ /**
2524
+ * SPDX-License-Identifier: Apache-2.0
2525
+ * Copyright FINOS FDC3 contributors - see NOTICE file
2526
+ */
2527
+ /** Constants representing the errors that can be encountered when calling the `open` method on the DesktopAgent object (`fdc3`). */
2528
+ var OpenError;
2529
+ (function (OpenError) {
2530
+ /** Returned if the specified application is not found.*/
2531
+ OpenError["AppNotFound"] = "AppNotFound";
2532
+ /** Returned if the specified application fails to launch correctly.*/
2533
+ OpenError["ErrorOnLaunch"] = "ErrorOnLaunch";
2534
+ /** Returned if the specified application launches but fails to add a context listener in order to receive the context passed to the `fdc3.open` call.*/
2535
+ OpenError["AppTimeout"] = "AppTimeout";
2536
+ /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
2537
+ OpenError["ResolverUnavailable"] = "ResolverUnavailable";
2538
+ /** 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.*/
2539
+ OpenError["MalformedContext"] = "MalformedContext";
2540
+ /** @experimental Returned if the specified Desktop Agent is not found, via a connected Desktop Agent Bridge.*/
2541
+ OpenError["DesktopAgentNotFound"] = "DesktopAgentNotFound";
2542
+ })(OpenError || (OpenError = {}));
2543
+ /** Constants representing the errors that can be encountered when calling the `findIntent`, `findIntentsByContext`, `raiseIntent` or `raiseIntentForContext` methods on the DesktopAgent (`fdc3`). */
2544
+ var ResolveError;
2545
+ (function (ResolveError) {
2546
+ /** SHOULD be returned if no apps are available that can resolve the intent and context combination.*/
2547
+ ResolveError["NoAppsFound"] = "NoAppsFound";
2548
+ /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
2549
+ ResolveError["ResolverUnavailable"] = "ResolverUnavailable";
2550
+ /** Returned if the user cancelled the resolution request, for example by closing or cancelling a resolver UI.*/
2551
+ ResolveError["UserCancelled"] = "UserCancelledResolution";
2552
+ /** 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.*/
2553
+ ResolveError["ResolverTimeout"] = "ResolverTimeout";
2554
+ /** Returned if a specified target application is not available or a new instance of it cannot be opened. */
2555
+ ResolveError["TargetAppUnavailable"] = "TargetAppUnavailable";
2556
+ /** Returned if a specified target application instance is not available, for example because it has been closed. */
2557
+ ResolveError["TargetInstanceUnavailable"] = "TargetInstanceUnavailable";
2558
+ /** 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.*/
2559
+ ResolveError["IntentDeliveryFailed"] = "IntentDeliveryFailed";
2560
+ /** 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.*/
2561
+ ResolveError["MalformedContext"] = "MalformedContext";
2562
+ /** @experimental Returned if the specified Desktop Agent is not found, via a connected Desktop Agent Bridge.*/
2563
+ ResolveError["DesktopAgentNotFound"] = "DesktopAgentNotFound";
2564
+ })(ResolveError || (ResolveError = {}));
2565
+ var ResultError;
2566
+ (function (ResultError) {
2567
+ /** Returned if the intent handler exited without returning a valid result (a promise resolving to a Context, Channel object or void). */
2568
+ ResultError["NoResultReturned"] = "NoResultReturned";
2569
+ /** Returned if the Intent handler function processing the raised intent throws an error or rejects the Promise it returned. */
2570
+ ResultError["IntentHandlerRejected"] = "IntentHandlerRejected";
2571
+ })(ResultError || (ResultError = {}));
2572
+ var ChannelError;
2573
+ (function (ChannelError) {
2574
+ /** Returned if the specified channel is not found when attempting to join a channel via the `joinUserChannel` function of the DesktopAgent (`fdc3`).*/
2575
+ ChannelError["NoChannelFound"] = "NoChannelFound";
2576
+ /** 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. */
2577
+ ChannelError["AccessDenied"] = "AccessDenied";
2578
+ /** SHOULD be returned when a channel cannot be created or retrieved via the `getOrCreateChannel` method of the DesktopAgent (`fdc3`).*/
2579
+ ChannelError["CreationFailed"] = "CreationFailed";
2580
+ /** 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.*/
2581
+ ChannelError["MalformedContext"] = "MalformedContext";
2582
+ })(ChannelError || (ChannelError = {}));
2583
+ var BridgingError;
2584
+ (function (BridgingError) {
2585
+ /** @experimental Returned if a Desktop Agent did not return a response, via Desktop Agent Bridging, within the alloted timeout. */
2586
+ BridgingError["ResponseTimedOut"] = "ResponseToBridgeTimedOut";
2587
+ /** @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. */
2588
+ BridgingError["AgentDisconnected"] = "AgentDisconnected";
2589
+ /** @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. */
2590
+ BridgingError["NotConnectedToBridge"] = "NotConnectedToBridge";
2591
+ /** @experimental Returned if a message to a Bridge deviates from the schema for that message sufficiently that it could not be processed. */
2592
+ BridgingError["MalformedMessage"] = "MalformedMessage";
2593
+ })(BridgingError || (BridgingError = {}));
2594
+
2595
+ /**
2596
+ * SPDX-License-Identifier: Apache-2.0
2597
+ * Copyright FINOS FDC3 contributors - see NOTICE file
2598
+ */
2599
+ var ContextTypes;
2600
+ (function (ContextTypes) {
2601
+ ContextTypes["Chart"] = "fdc3.chart";
2602
+ ContextTypes["ChatInitSettings"] = "fdc3.chat.initSettings";
2603
+ ContextTypes["ChatRoom"] = "fdc3.chat.room";
2604
+ ContextTypes["Contact"] = "fdc3.contact";
2605
+ ContextTypes["ContactList"] = "fdc3.contactList";
2606
+ ContextTypes["Country"] = "fdc3.country";
2607
+ ContextTypes["Currency"] = "fdc3.currency";
2608
+ ContextTypes["Email"] = "fdc3.email";
2609
+ ContextTypes["Instrument"] = "fdc3.instrument";
2610
+ ContextTypes["InstrumentList"] = "fdc3.instrumentList";
2611
+ ContextTypes["Interaction"] = "fdc3.interaction";
2612
+ ContextTypes["Nothing"] = "fdc3.nothing";
2613
+ ContextTypes["Organization"] = "fdc3.organization";
2614
+ ContextTypes["Portfolio"] = "fdc3.portfolio";
2615
+ ContextTypes["Position"] = "fdc3.position";
2616
+ ContextTypes["ChatSearchCriteria"] = "fdc3.chat.searchCriteria";
2617
+ ContextTypes["TimeRange"] = "fdc3.timerange";
2618
+ ContextTypes["TransactionResult"] = "fdc3.transactionResult";
2619
+ ContextTypes["Valuation"] = "fdc3.valuation";
2620
+ })(ContextTypes || (ContextTypes = {}));
2621
+
2622
+ /**
2623
+ * SPDX-License-Identifier: Apache-2.0
2624
+ * Copyright FINOS FDC3 contributors - see NOTICE file
2625
+ */
2626
+ var Intents;
2627
+ (function (Intents) {
2628
+ Intents["CreateInteraction"] = "CreateInteraction";
2629
+ Intents["SendChatMessage"] = "SendChatMessage";
2630
+ Intents["StartCall"] = "StartCall";
2631
+ Intents["StartChat"] = "StartChat";
2632
+ Intents["StartEmail"] = "StartEmail";
2633
+ Intents["ViewAnalysis"] = "ViewAnalysis";
2634
+ Intents["ViewChat"] = "ViewChat";
2635
+ Intents["ViewChart"] = "ViewChart";
2636
+ Intents["ViewContact"] = "ViewContact";
2637
+ Intents["ViewHoldings"] = "ViewHoldings";
2638
+ Intents["ViewInstrument"] = "ViewInstrument";
2639
+ Intents["ViewInteractions"] = "ViewInteractions";
2640
+ Intents["ViewMessages"] = "ViewMessages";
2641
+ Intents["ViewNews"] = "ViewNews";
2642
+ Intents["ViewOrders"] = "ViewOrders";
2643
+ Intents["ViewProfile"] = "ViewProfile";
2644
+ Intents["ViewQuote"] = "ViewQuote";
2645
+ Intents["ViewResearch"] = "ViewResearch";
2646
+ })(Intents || (Intents = {}));
1340
2647
 
1341
2648
  class DesktopAgent {
1342
2649
  constructor(intentsController, applicationController, channelsController) {
@@ -1372,7 +2679,10 @@
1372
2679
  open(target, context) {
1373
2680
  return __awaiter(this, void 0, void 0, function* () {
1374
2681
  targetAppDecoder.runWithException(target);
1375
- optionalContextDecoder.runWithException(context);
2682
+ const contextDecoderResult = optionalContextDecoder.run(context);
2683
+ if (!contextDecoderResult.ok) {
2684
+ throw new Error(OpenError.MalformedContext);
2685
+ }
1376
2686
  return this.applicationController.open({ commandId: generateCommandId(), target, context });
1377
2687
  });
1378
2688
  }
@@ -1395,7 +2705,10 @@
1395
2705
  }
1396
2706
  broadcast(context) {
1397
2707
  return __awaiter(this, void 0, void 0, function* () {
1398
- contextDecoder.runWithException(context);
2708
+ const contextDecoderResult = contextDecoder.run(context);
2709
+ if (!contextDecoderResult.ok) {
2710
+ throw new Error(ChannelError.MalformedContext);
2711
+ }
1399
2712
  return this.channelsController.broadcast(generateCommandId(), context);
1400
2713
  });
1401
2714
  }
@@ -1419,7 +2732,7 @@
1419
2732
  nonEmptyStringDecoder.runWithException(intent);
1420
2733
  const contextDecoderResult = optionalContextDecoder.run(context);
1421
2734
  if (!contextDecoderResult.ok) {
1422
- throw new Error(`Invalid Context: ${contextDecoderResult.error}`);
2735
+ throw new Error(ResolveError.MalformedContext);
1423
2736
  }
1424
2737
  optionalNonEmptyStringDecoder.runWithException(resultType);
1425
2738
  return this.intentsController.findIntent({ commandId: generateCommandId(), intent, context: contextDecoderResult.result, resultType });
@@ -1429,7 +2742,7 @@
1429
2742
  return __awaiter(this, void 0, void 0, function* () {
1430
2743
  const contextDecoderResult = contextDecoder.run(context);
1431
2744
  if (!contextDecoderResult.ok) {
1432
- throw new Error(`Invalid Context: ${contextDecoderResult.error}`);
2745
+ throw new Error(ResolveError.MalformedContext);
1433
2746
  }
1434
2747
  optionalNonEmptyStringDecoder.runWithException(resultType);
1435
2748
  return this.intentsController.findIntentsByContext({ commandId: generateCommandId(), context: contextDecoderResult.result, resultType });
@@ -1438,14 +2751,20 @@
1438
2751
  raiseIntent(intent, context, app) {
1439
2752
  return __awaiter(this, void 0, void 0, function* () {
1440
2753
  nonEmptyStringDecoder.runWithException(intent);
1441
- contextDecoder.runWithException(context);
2754
+ const contextDecoderResult = contextDecoder.run(context);
2755
+ if (!contextDecoderResult.ok) {
2756
+ throw new Error(ResolveError.MalformedContext);
2757
+ }
1442
2758
  optionalAppIdentifier.runWithException(app);
1443
2759
  return this.intentsController.raiseIntent({ commandId: generateCommandId(), intent, context, target: app });
1444
2760
  });
1445
2761
  }
1446
2762
  raiseIntentForContext(context, app) {
1447
2763
  return __awaiter(this, void 0, void 0, function* () {
1448
- contextDecoder.runWithException(context);
2764
+ const contextDecoderResult = contextDecoder.run(context);
2765
+ if (!contextDecoderResult.ok) {
2766
+ throw new Error(ResolveError.MalformedContext);
2767
+ }
1449
2768
  optionalTargetApp.runWithException(app);
1450
2769
  return this.intentsController.raiseIntentForContext({ commandId: generateCommandId(), context, target: app });
1451
2770
  });
@@ -1522,7 +2841,10 @@
1522
2841
  }
1523
2842
  broadcast(context) {
1524
2843
  return __awaiter(this, void 0, void 0, function* () {
1525
- contextDecoder.runWithException(context);
2844
+ const contextDecoderResult = contextDecoder.run(context);
2845
+ if (!contextDecoderResult.ok) {
2846
+ throw new Error(ChannelError.MalformedContext);
2847
+ }
1526
2848
  return this.channelsController.broadcast(generateCommandId(), context, this.id);
1527
2849
  });
1528
2850
  }
@@ -1567,7 +2889,7 @@
1567
2889
  return this.mapChannelsDelimiterToFDC3Type(withoutPrefix);
1568
2890
  }
1569
2891
  parseFDC3ContextToGlueContexts(context) {
1570
- const { type } = context, rest = __rest$1(context, ["type"]);
2892
+ const { type } = context, rest = __rest$2(context, ["type"]);
1571
2893
  const parsedType = this.mapFDC3TypeToChannelsDelimiter(type);
1572
2894
  return { path: `${this.channelsFdc3DataPrefix}${parsedType}`, value: rest };
1573
2895
  }
@@ -1582,137 +2904,6 @@
1582
2904
  }
1583
2905
  }
1584
2906
 
1585
- /**
1586
- * SPDX-License-Identifier: Apache-2.0
1587
- * Copyright FINOS FDC3 contributors - see NOTICE file
1588
- */
1589
- /** Constants representing the errors that can be encountered when calling the `open` method on the DesktopAgent object (`fdc3`). */
1590
- var OpenError;
1591
- (function (OpenError) {
1592
- /** Returned if the specified application is not found.*/
1593
- OpenError["AppNotFound"] = "AppNotFound";
1594
- /** Returned if the specified application fails to launch correctly.*/
1595
- OpenError["ErrorOnLaunch"] = "ErrorOnLaunch";
1596
- /** Returned if the specified application launches but fails to add a context listener in order to receive the context passed to the `fdc3.open` call.*/
1597
- OpenError["AppTimeout"] = "AppTimeout";
1598
- /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
1599
- OpenError["ResolverUnavailable"] = "ResolverUnavailable";
1600
- /** 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.*/
1601
- OpenError["MalformedContext"] = "MalformedContext";
1602
- })(OpenError || (OpenError = {}));
1603
- /** Constants representing the errors that can be encountered when calling the `findIntent`, `findIntentsByContext`, `raiseIntent` or `raiseIntentForContext` methods on the DesktopAgent (`fdc3`). */
1604
- var ResolveError;
1605
- (function (ResolveError) {
1606
- /** SHOULD be returned if no apps are available that can resolve the intent and context combination.*/
1607
- ResolveError["NoAppsFound"] = "NoAppsFound";
1608
- /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
1609
- ResolveError["ResolverUnavailable"] = "ResolverUnavailable";
1610
- /** Returned if the user cancelled the resolution request, for example by closing or cancelling a resolver UI.*/
1611
- ResolveError["UserCancelled"] = "UserCancelledResolution";
1612
- /** 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.*/
1613
- ResolveError["ResolverTimeout"] = "ResolverTimeout";
1614
- /** Returned if a specified target application is not available or a new instance of it cannot be opened. */
1615
- ResolveError["TargetAppUnavailable"] = "TargetAppUnavailable";
1616
- /** Returned if a specified target application instance is not available, for example because it has been closed. */
1617
- ResolveError["TargetInstanceUnavailable"] = "TargetInstanceUnavailable";
1618
- /** 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.*/
1619
- ResolveError["IntentDeliveryFailed"] = "IntentDeliveryFailed";
1620
- /** 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.*/
1621
- ResolveError["MalformedContext"] = "MalformedContext";
1622
- })(ResolveError || (ResolveError = {}));
1623
- var ResultError;
1624
- (function (ResultError) {
1625
- /** Returned if the intent handler exited without returning a valid result (a promise resolving to a Context, Channel object or void). */
1626
- ResultError["NoResultReturned"] = "NoResultReturned";
1627
- /** Returned if the Intent handler function processing the raised intent throws an error or rejects the Promise it returned. */
1628
- ResultError["IntentHandlerRejected"] = "IntentHandlerRejected";
1629
- })(ResultError || (ResultError = {}));
1630
- var ChannelError;
1631
- (function (ChannelError) {
1632
- /** Returned if the specified channel is not found when attempting to join a channel via the `joinUserChannel` function of the DesktopAgent (`fdc3`).*/
1633
- ChannelError["NoChannelFound"] = "NoChannelFound";
1634
- /** 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. */
1635
- ChannelError["AccessDenied"] = "AccessDenied";
1636
- /** SHOULD be returned when a channel cannot be created or retrieved via the `getOrCreateChannel` method of the DesktopAgent (`fdc3`).*/
1637
- ChannelError["CreationFailed"] = "CreationFailed";
1638
- /** 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.*/
1639
- ChannelError["MalformedContext"] = "MalformedContext";
1640
- })(ChannelError || (ChannelError = {}));
1641
-
1642
- var ContextTypes;
1643
- (function (ContextTypes) {
1644
- ContextTypes["Chart"] = "fdc3.chart";
1645
- ContextTypes["ChatInitSettings"] = "fdc3.chat.initSettings";
1646
- ContextTypes["Contact"] = "fdc3.contact";
1647
- ContextTypes["ContactList"] = "fdc3.contactList";
1648
- ContextTypes["Country"] = "fdc3.country";
1649
- ContextTypes["Currency"] = "fdc3.currency";
1650
- ContextTypes["Email"] = "fdc3.email";
1651
- ContextTypes["Instrument"] = "fdc3.instrument";
1652
- ContextTypes["InstrumentList"] = "fdc3.instrumentList";
1653
- ContextTypes["Organization"] = "fdc3.organization";
1654
- ContextTypes["Portfolio"] = "fdc3.portfolio";
1655
- ContextTypes["Position"] = "fdc3.position";
1656
- ContextTypes["Nothing"] = "fdc3.nothing";
1657
- ContextTypes["TimeRange"] = "fdc3.timerange";
1658
- ContextTypes["Valuation"] = "fdc3.valuation";
1659
- })(ContextTypes || (ContextTypes = {}));
1660
-
1661
- // To parse this data:
1662
- //
1663
- // import { Convert, Chart, ChatInitSettings, Contact, ContactList, Context, Country, Currency, Email, Instrument, InstrumentList, Nothing, Organization, Portfolio, Position, TimeRange, Valuation } from "./file";
1664
- //
1665
- // const chart = Convert.toChart(json);
1666
- // const chatInitSettings = Convert.toChatInitSettings(json);
1667
- // const contact = Convert.toContact(json);
1668
- // const contactList = Convert.toContactList(json);
1669
- // const context = Convert.toContext(json);
1670
- // const country = Convert.toCountry(json);
1671
- // const currency = Convert.toCurrency(json);
1672
- // const email = Convert.toEmail(json);
1673
- // const instrument = Convert.toInstrument(json);
1674
- // const instrumentList = Convert.toInstrumentList(json);
1675
- // const nothing = Convert.toNothing(json);
1676
- // const organization = Convert.toOrganization(json);
1677
- // const portfolio = Convert.toPortfolio(json);
1678
- // const position = Convert.toPosition(json);
1679
- // const timeRange = Convert.toTimeRange(json);
1680
- // const valuation = Convert.toValuation(json);
1681
- //
1682
- // These functions will throw an error if the JSON doesn't
1683
- // match the expected interface, even if the JSON is valid.
1684
- var Style;
1685
- (function (Style) {
1686
- Style["Bar"] = "bar";
1687
- Style["Candle"] = "candle";
1688
- Style["Custom"] = "custom";
1689
- Style["Heatmap"] = "heatmap";
1690
- Style["Histogram"] = "histogram";
1691
- Style["Line"] = "line";
1692
- Style["Mountain"] = "mountain";
1693
- Style["Pie"] = "pie";
1694
- Style["Scatter"] = "scatter";
1695
- Style["StackedBar"] = "stacked-bar";
1696
- })(Style || (Style = {}));
1697
-
1698
- var Intents;
1699
- (function (Intents) {
1700
- Intents["StartCall"] = "StartCall";
1701
- Intents["StartChat"] = "StartChat";
1702
- Intents["StartEmail"] = "StartEmail";
1703
- Intents["ViewAnalysis"] = "ViewAnalysis";
1704
- Intents["ViewChart"] = "ViewChart";
1705
- Intents["ViewContact"] = "ViewContact";
1706
- Intents["ViewHoldings"] = "ViewHoldings";
1707
- Intents["ViewInstrument"] = "ViewInstrument";
1708
- Intents["ViewInteractions"] = "ViewInteractions";
1709
- Intents["ViewNews"] = "ViewNews";
1710
- Intents["ViewOrders"] = "ViewOrders";
1711
- Intents["ViewProfile"] = "ViewProfile";
1712
- Intents["ViewQuote"] = "ViewQuote";
1713
- Intents["ViewResearch"] = "ViewResearch";
1714
- })(Intents || (Intents = {}));
1715
-
1716
2907
  class UserChannel {
1717
2908
  constructor(channelsController, glueChannel) {
1718
2909
  this.channelsController = channelsController;
@@ -1738,7 +2929,10 @@
1738
2929
  }
1739
2930
  broadcast(context) {
1740
2931
  return __awaiter(this, void 0, void 0, function* () {
1741
- contextDecoder.runWithException(context);
2932
+ const contextDecoderResult = contextDecoder.run(context);
2933
+ if (!contextDecoderResult.ok) {
2934
+ throw new Error(ChannelError.MalformedContext);
2935
+ }
1742
2936
  return this.channelsController.broadcast(generateCommandId(), context, this.id);
1743
2937
  });
1744
2938
  }
@@ -1797,6 +2991,19 @@
1797
2991
  this.channelsController = channelsController;
1798
2992
  this.channelsFactory = channelsFactory;
1799
2993
  this.glueEventsController = glueEventsController;
2994
+ this.ioToFDC3ErrorsDict = {
2995
+ [IO_ERRORS.USER_CANCELLED]: ResolveError.UserCancelled,
2996
+ [IO_ERRORS.TIMEOUT_HIT]: ResolveError.IntentDeliveryFailed,
2997
+ [IO_ERRORS.TARGET_INSTANCE_UNAVAILABLE]: ResolveError.TargetInstanceUnavailable,
2998
+ [IO_ERRORS.RESOLVER_UNAVAILABLE]: ResolveError.ResolverUnavailable,
2999
+ [IO_ERRORS.RESOLVER_TIMEOUT]: ResolveError.ResolverTimeout,
3000
+ [IO_ERRORS.INVALID_RESOLVER_RESPONSE]: ResolveError.IntentDeliveryFailed,
3001
+ [IO_ERRORS.INTENT_NOT_FOUND]: ResolveError.NoAppsFound,
3002
+ [IO_ERRORS.INTENT_DELIVERY_FAILED]: ResolveError.IntentDeliveryFailed,
3003
+ [IO_ERRORS.HANDLER_NOT_FOUND]: ResolveError.NoAppsFound,
3004
+ [IO_ERRORS.CALLER_NOT_DEFINED]: ResolveError.IntentDeliveryFailed,
3005
+ [IO_ERRORS.INTENT_HANDLER_REJECTION]: ResultError.IntentHandlerRejected
3006
+ };
1800
3007
  }
1801
3008
  get logger() {
1802
3009
  if (!this._logger) {
@@ -1805,9 +3012,10 @@
1805
3012
  return this._logger;
1806
3013
  }
1807
3014
  findIntent({ commandId, intent, context, resultType }) {
3015
+ var _a;
1808
3016
  return __awaiter(this, void 0, void 0, function* () {
1809
3017
  yield this.glueController.gluePromise;
1810
- this.logger.info(`[${commandId}] - findIntent() invoked for intent ${intent} with contextType ${context === null || context === void 0 ? void 0 : context.type} and resultType ${resultType}`);
3018
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - findIntent() invoked for intent ${intent} with contextType ${context === null || context === void 0 ? void 0 : context.type} and resultType ${resultType}`);
1811
3019
  const glueIntents = yield this.glueController.findIntents({ name: intent });
1812
3020
  if (!glueIntents.length) {
1813
3021
  throw { message: ResolveError.NoAppsFound, reason: `There are no apps handling the passed intent ${intent}` };
@@ -1828,14 +3036,15 @@
1828
3036
  });
1829
3037
  }
1830
3038
  findIntentsByContext({ commandId, context, resultType }) {
3039
+ var _a, _b;
1831
3040
  return __awaiter(this, void 0, void 0, function* () {
1832
3041
  yield this.glueController.gluePromise;
1833
- this.logger.info(`[${commandId}] - findIntentsByContext() invoked for context type ${context.type} and resultType ${resultType}`);
3042
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - findIntentsByContext() invoked for context type ${context.type} and resultType ${resultType}`);
1834
3043
  const glueIntents = yield this.glueController.findIntents({ contextType: context.type, resultType });
1835
3044
  if (!glueIntents.length) {
1836
3045
  throw { message: ResolveError.NoAppsFound, reason: `No apps registering intent with contextType ${context.type} ${resultType ? `and resultType ${resultType}` : ""}` };
1837
3046
  }
1838
- this.logger.info(`[${commandId}] - parsing glue intents to fdc3 intents and returning`);
3047
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - parsing glue intents to fdc3 intents and returning`);
1839
3048
  return glueIntents.map((glueIntent) => {
1840
3049
  const intentWithFilteredHandlers = this.getGlueIntentWithFilteredHandlers(glueIntent, { contextType: context.type, resultType });
1841
3050
  return this.convertGlue42IntentToFDC3Intent(intentWithFilteredHandlers);
@@ -1843,10 +3052,10 @@
1843
3052
  });
1844
3053
  }
1845
3054
  raiseIntent({ commandId, intent, context, target }) {
1846
- var _a;
3055
+ var _a, _b, _c, _d, _e;
1847
3056
  return __awaiter(this, void 0, void 0, function* () {
1848
3057
  yield this.glueController.gluePromise;
1849
- this.logger.info(`[${commandId}] - raiseIntent() invoked for intent ${intent} with contextType: ${context.type} and target: ${target}`);
3058
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - raiseIntent() invoked for intent ${intent} with contextType: ${context.type} and target: ${target}`);
1850
3059
  const glueContext = { type: context.type, data: Object.assign({}, context) };
1851
3060
  const searchedGlueIntent = (yield this.glueController.findIntents({ name: intent })).find(glueIntent => glueIntent.name === intent);
1852
3061
  if (!searchedGlueIntent) {
@@ -1854,18 +3063,18 @@
1854
3063
  }
1855
3064
  const filteredGlueIntent = this.filterGlueIntentHandlers({ commandId, intent: searchedGlueIntent, context, target });
1856
3065
  if (!target) {
1857
- this.logger.info(`[${commandId}] - raising intent ${intent} with contextType ${context.type} and handlers ${filteredGlueIntent.handlers.map(h => h.applicationName && h.instanceId)}`);
3066
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - raising intent ${intent} with contextType ${context.type} and handlers ${filteredGlueIntent.handlers.map(h => h.applicationName && h.instanceId)}`);
1858
3067
  return this.invokeRaiseIntent(commandId, { intent, context: glueContext, handlers: filteredGlueIntent.handlers });
1859
3068
  }
1860
3069
  if (typeof target === "string" || !target.instanceId) {
1861
- this.logger.info(`[${commandId}] - target app ${target.appId} is a valid handler. Raising intent ${intent} with contextType ${context.type} and handlers ${filteredGlueIntent.handlers}`);
3070
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.info(`[${commandId}] - target app ${target.appId} is a valid handler. Raising intent ${intent} with contextType ${context.type} and handlers ${filteredGlueIntent.handlers}`);
1862
3071
  return this.invokeRaiseIntent(commandId, {
1863
3072
  intent,
1864
3073
  context: glueContext,
1865
- target: { app: target.appId, instance: (_a = filteredGlueIntent.handlers.find((h) => h.instanceId)) === null || _a === void 0 ? void 0 : _a.instanceId }
3074
+ target: { app: target.appId, instance: (_d = filteredGlueIntent.handlers.find((h) => h.instanceId)) === null || _d === void 0 ? void 0 : _d.instanceId }
1866
3075
  });
1867
3076
  }
1868
- this.logger.info(`[${commandId}] - raising intent ${intent} with contextType ${context.type} to target instance of app ${target.appId} and id ${target.instanceId}`);
3077
+ (_e = this.logger) === null || _e === void 0 ? void 0 : _e.info(`[${commandId}] - raising intent ${intent} with contextType ${context.type} to target instance of app ${target.appId} and id ${target.instanceId}`);
1869
3078
  return this.invokeRaiseIntent(commandId, {
1870
3079
  intent,
1871
3080
  context: glueContext,
@@ -1874,24 +3083,43 @@
1874
3083
  });
1875
3084
  }
1876
3085
  raiseIntentForContext({ commandId, context, target }) {
3086
+ var _a, _b, _c;
1877
3087
  return __awaiter(this, void 0, void 0, function* () {
1878
3088
  yield this.glueController.gluePromise;
1879
- this.logger.info(`[${commandId}] - raiseIntentForContext() invoked with contextType ${context.type} and target ${target}`);
1880
- const appIntents = yield this.findIntentsByContext({ commandId, context });
1881
- if (!appIntents || appIntents.length === 0) {
1882
- throw {
1883
- message: ResolveError.NoAppsFound,
1884
- reason: `No apps registering intent with contextType ${context.type} ${target ? `and target ${JSON.stringify(target)}` : ""}`
1885
- };
3089
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - raiseIntentForContext() invoked with contextType ${context.type} and target ${target}`);
3090
+ const filteredHandlersMethodExist = this.glueController.doesFilterHandlersExist();
3091
+ const getIntentsMethodExist = this.glueController.doesGetIntentsExist();
3092
+ if (!filteredHandlersMethodExist || !getIntentsMethodExist || target) {
3093
+ return this.legacyRaiseIntentForContext({ commandId, context, target });
1886
3094
  }
1887
- return this.raiseIntent({ commandId, intent: appIntents[0].intent.name, context, target });
3095
+ const filteredHandlersResPromise = this.glueController.filterHandlers({ contextTypes: [context.type] })
3096
+ .catch((err) => {
3097
+ throw this.parseIoToFdc3Error(err);
3098
+ });
3099
+ const { handlers } = yield filteredHandlersResPromise;
3100
+ if (!handlers.length) {
3101
+ const errorMsg = `${ResolveError.NoAppsFound} - Cannot find Intent Handlers for intents with context type ${context.type}`;
3102
+ (_b = this._logger) === null || _b === void 0 ? void 0 : _b.warn(`[${commandId}] - ${errorMsg}`);
3103
+ throw new Error(ResolveError.NoAppsFound);
3104
+ }
3105
+ if (handlers.length > 1) {
3106
+ return this.legacyRaiseIntentForContext({ commandId, context, target });
3107
+ }
3108
+ const handler = handlers[0];
3109
+ const { intents } = yield this.glueController.getIntents(handler);
3110
+ const validIntent = intents.find((intentInfo) => { var _a; return (_a = intentInfo.contextTypes) === null || _a === void 0 ? void 0 : _a.includes(context.type); });
3111
+ if (!validIntent) {
3112
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.warn(`[${commandId}] - ${ResolveError.IntentDeliveryFailed} - There's no valid intent for handler ${JSON.stringify(handler)} and context type ${context.type}`);
3113
+ throw new Error(ResolveError.IntentDeliveryFailed);
3114
+ }
3115
+ return this.invokeRaiseIntent(commandId, { intent: validIntent.intent, context, target: { app: handler.applicationName, instance: handler.instanceId } });
1888
3116
  });
1889
3117
  }
1890
3118
  addIntentListener({ commandId, intent, handler }) {
1891
- var _a, _b;
3119
+ var _a, _b, _c;
1892
3120
  return __awaiter(this, void 0, void 0, function* () {
1893
3121
  yield this.glueController.gluePromise;
1894
- this.logger.info(`[${commandId}] - addIntentListener() invoked for intent ${intent}`);
3122
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - addIntentListener() invoked for intent ${intent}`);
1895
3123
  const wrappedHandler = this.getWrappedIntentHandler(handler);
1896
3124
  const myInstance = this.glueController.getMyInteropInstance();
1897
3125
  const myApplication = this.glueController.getApplication(myInstance.applicationName);
@@ -1899,11 +3127,11 @@
1899
3127
  const globalBrowserNamespace = window.glue42core || window.iobrowser;
1900
3128
  const globalDesktopNamespace = window.glue42gd || window.iodesktop;
1901
3129
  if (globalBrowserNamespace) {
1902
- appConfigIntentDef = (_a = myApplication === null || myApplication === void 0 ? void 0 : myApplication.userProperties.intents) === null || _a === void 0 ? void 0 : _a.find((appIntent) => appIntent.name === intent);
3130
+ appConfigIntentDef = (_b = myApplication === null || myApplication === void 0 ? void 0 : myApplication.userProperties.intents) === null || _b === void 0 ? void 0 : _b.find((appIntent) => appIntent.name === intent);
1903
3131
  }
1904
3132
  if (globalDesktopNamespace) {
1905
3133
  const appConfig = yield myApplication.getConfiguration();
1906
- appConfigIntentDef = (_b = appConfig === null || appConfig === void 0 ? void 0 : appConfig.intents) === null || _b === void 0 ? void 0 : _b.find((appIntent) => appIntent.name === intent);
3134
+ appConfigIntentDef = (_c = appConfig === null || appConfig === void 0 ? void 0 : appConfig.intents) === null || _c === void 0 ? void 0 : _c.find((appIntent) => appIntent.name === intent);
1907
3135
  }
1908
3136
  const intentRequest = {
1909
3137
  intent,
@@ -1918,32 +3146,34 @@
1918
3146
  });
1919
3147
  }
1920
3148
  filterGlueIntentHandlers({ commandId, intent, context, target }) {
3149
+ var _a, _b;
1921
3150
  let filteredGlueIntent;
1922
3151
  filteredGlueIntent = this.filterIntentHandlersByContext(intent, context);
1923
3152
  if (!target) {
1924
- this.logger.info(`[${commandId}] - There's no passed target, intent handlers are filtered only by context type`);
3153
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - There's no passed target, intent handlers are filtered only by context type`);
1925
3154
  return filteredGlueIntent;
1926
3155
  }
1927
- this.logger.log(`[${commandId}] - filtering handlers by target (${JSON.stringify(target)}) for intent ${intent.name}`);
3156
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.log(`[${commandId}] - filtering handlers by target (${JSON.stringify(target)}) for intent ${intent.name}`);
1928
3157
  filteredGlueIntent = this.filterIntentHandlersByTarget({ intent, target, commandId });
1929
3158
  return filteredGlueIntent;
1930
3159
  }
1931
3160
  filterIntentHandlersByTarget({ intent, target, commandId }) {
3161
+ var _a, _b, _c, _d;
1932
3162
  const appName = typeof target === "string" ? target : target.appId;
1933
3163
  const instanceId = typeof target === "string" ? undefined : target.instanceId;
1934
- this.logger.info(`[${commandId}] - Checking if application with name ${appName} exists`);
3164
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - Checking if application with name ${appName} exists`);
1935
3165
  const app = this.glueController.getApplication(appName);
1936
3166
  const serverInstances = this.serverInstanceAsIntentHandler(intent.name);
1937
3167
  if (!app && (typeof target === "string" || !target.instanceId || !serverInstances.length)) {
1938
3168
  throw { message: ResolveError.TargetAppUnavailable, reason: `There's no app with appId ${appName}` };
1939
3169
  }
1940
- this.logger.info(`[${commandId}] - target app ${appName} found. Filtering handlers by applicationName: ${appName}`);
3170
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - target app ${appName} found. Filtering handlers by applicationName: ${appName}`);
1941
3171
  const validHandlersByApplicationName = intent.handlers.filter((handler) => handler.applicationName === appName);
1942
3172
  if (!validHandlersByApplicationName.length) {
1943
3173
  throw { message: ResolveError.NoAppsFound, reason: `Intent ${intent.name} exists but there's no app with appId ${appName} registering it` };
1944
3174
  }
1945
3175
  if (!instanceId) {
1946
- this.logger.log(`[${commandId}] - returning all handlers for intent ${intent.name} and target: ${JSON.stringify(target)}`);
3176
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.log(`[${commandId}] - returning all handlers for intent ${intent.name} and target: ${JSON.stringify(target)}`);
1947
3177
  return { name: intent.name, handlers: validHandlersByApplicationName };
1948
3178
  }
1949
3179
  const isValidInstanceOfTheApp = app
@@ -1952,7 +3182,7 @@
1952
3182
  if (!isValidInstanceOfTheApp) {
1953
3183
  throw { message: ResolveError.TargetInstanceUnavailable, reason: `There's no instance with id ${instanceId} of the passed app ${appName}` };
1954
3184
  }
1955
- this.logger.info(`[${commandId}] - Filtering handlers by instanceId: ${instanceId}`);
3185
+ (_d = this.logger) === null || _d === void 0 ? void 0 : _d.info(`[${commandId}] - Filtering handlers by instanceId: ${instanceId}`);
1956
3186
  const validHandlersByInstanceId = validHandlersByApplicationName.filter((handler) => handler.instanceId === instanceId);
1957
3187
  if (!validHandlersByInstanceId.length) {
1958
3188
  throw { message: ResolveError.IntentDeliveryFailed, reason: `There's no instance with id ${instanceId} of app ${appName} registering intent ${intent.name}` };
@@ -1974,9 +3204,17 @@
1974
3204
  return filteredGlueIntent;
1975
3205
  }
1976
3206
  getResult(commandId, glueIntentResult) {
3207
+ var _a, _b, _c;
1977
3208
  return __awaiter(this, void 0, void 0, function* () {
1978
- this.logger.info(`[${commandId}] - getResult() of IntentResolution invoked`);
3209
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - getResult() of IntentResolution invoked`);
1979
3210
  const { result } = glueIntentResult;
3211
+ if (result.fdc3error) {
3212
+ throw result.fdc3error;
3213
+ }
3214
+ if (!result || typeof result !== "object" || Array.isArray(result) || (isValidNonEmptyObject(result) && !result.fdc3intentContext && !result.fdc3intentChannel && !result.fdc3error)) {
3215
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.warn(`[${commandId}] - ${ResultError.NoResultReturned} - The intent handler exited without returning a valid result - a promise resolving to a Context, Channel object or void`);
3216
+ throw new Error(ResultError.NoResultReturned);
3217
+ }
1980
3218
  if (!isValidNonEmptyObject(result)) {
1981
3219
  return;
1982
3220
  }
@@ -1984,7 +3222,7 @@
1984
3222
  return result;
1985
3223
  }
1986
3224
  if (result.fdc3intentContext) {
1987
- return result.fdc3intentContext;
3225
+ return result.fdc3intentContext.payload;
1988
3226
  }
1989
3227
  const { fdc3intentChannel } = result;
1990
3228
  if (fdc3intentChannel.type === "user") {
@@ -2005,7 +3243,7 @@
2005
3243
  }
2006
3244
  };
2007
3245
  yield this.glueController.invokeSystemMethod(joinChannelArgs, glueIntentResult.handler.instanceId);
2008
- this.logger.info(`[${commandId}] - returning private channel`);
3246
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.info(`[${commandId}] - returning private channel`);
2009
3247
  return channel.toApi();
2010
3248
  });
2011
3249
  }
@@ -2038,10 +3276,10 @@
2038
3276
  if (isContext(data)) {
2039
3277
  return IntentHandlerResultTypes.Context;
2040
3278
  }
2041
- throw new Error("Async handler function should return a promise that resolves to a Context or Channel");
2042
3279
  }
2043
3280
  getWrappedIntentHandler(handler) {
2044
3281
  const wrappedHandler = (glue42Context, caller) => __awaiter(this, void 0, void 0, function* () {
3282
+ var _a;
2045
3283
  const contextMetadata = caller
2046
3284
  ? {
2047
3285
  source: {
@@ -2050,14 +3288,26 @@
2050
3288
  }
2051
3289
  }
2052
3290
  : undefined;
2053
- const handlerResult = yield handler(Object.assign(Object.assign({}, glue42Context.data), { type: glue42Context.type || "" }), contextMetadata);
3291
+ let handlerResult;
3292
+ try {
3293
+ handlerResult = yield handler(Object.assign(Object.assign({}, glue42Context.data), { type: glue42Context.type || "" }), contextMetadata);
3294
+ }
3295
+ catch (error) {
3296
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.warn(typeof error === "string" ? error : error.message || JSON.stringify(error));
3297
+ throw new Error(ResultError.IntentHandlerRejected);
3298
+ }
2054
3299
  if (!handlerResult) {
2055
3300
  return;
2056
3301
  }
2057
3302
  const handlerResultType = this.getResultType(handlerResult);
3303
+ if (!handlerResultType) {
3304
+ return {
3305
+ fdc3error: { message: ResultError.NoResultReturned, reason: "The intent handler exited without returning a valid result - a promise resolving to a Context, Channel object or void" }
3306
+ };
3307
+ }
2058
3308
  return handlerResultType === IntentHandlerResultTypes.Channel
2059
3309
  ? { fdc3intentChannel: extractChannelMetadata(handlerResult) }
2060
- : { fdc3intentContext: handlerResult };
3310
+ : { fdc3intentContext: { contextType: handlerResult.type, payload: handlerResult } };
2061
3311
  });
2062
3312
  return wrappedHandler;
2063
3313
  }
@@ -2098,13 +3348,34 @@
2098
3348
  };
2099
3349
  }
2100
3350
  catch (error) {
2101
- throw { message: ResolveError.IntentDeliveryFailed, reason: typeof error === "string" ? error : JSON.stringify(error) };
3351
+ throw this.parseIoToFdc3Error(error);
3352
+ }
3353
+ });
3354
+ }
3355
+ parseIoToFdc3Error(error) {
3356
+ const ioError = Object.keys(this.ioToFDC3ErrorsDict).find(((ioError) => { var _a; return (_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(ioError); }));
3357
+ const fdc3Error = ioError ? this.ioToFDC3ErrorsDict[ioError] : ResolveError.IntentDeliveryFailed;
3358
+ const stringifiedError = typeof error === "string" ? error : JSON.stringify(error);
3359
+ const reason = error instanceof Error ? error.message : stringifiedError;
3360
+ return { message: fdc3Error, reason };
3361
+ }
3362
+ legacyRaiseIntentForContext({ commandId, context, target }) {
3363
+ var _a;
3364
+ return __awaiter(this, void 0, void 0, function* () {
3365
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - raiseIntentForContext() invoked with contextType ${context.type} and target ${target}`);
3366
+ const appIntents = yield this.findIntentsByContext({ commandId, context });
3367
+ if (!appIntents || appIntents.length === 0) {
3368
+ throw {
3369
+ message: ResolveError.NoAppsFound,
3370
+ reason: `No apps registering intent with contextType ${context.type} ${target ? `and target ${JSON.stringify(target)}` : ""}`
3371
+ };
2102
3372
  }
3373
+ return this.raiseIntent({ commandId, intent: appIntents[0].intent.name, context, target });
2103
3374
  });
2104
3375
  }
2105
3376
  }
2106
3377
 
2107
- var version = "2.1.2";
3378
+ var version = "2.2.0";
2108
3379
 
2109
3380
  class ApplicationsController {
2110
3381
  constructor(glueController, appsStateStore, glueEventsController) {
@@ -2120,9 +3391,10 @@
2120
3391
  return this._logger;
2121
3392
  }
2122
3393
  open({ commandId, target, context }) {
3394
+ var _a, _b, _c, _d;
2123
3395
  return __awaiter(this, void 0, void 0, function* () {
2124
3396
  yield this.glueController.gluePromise;
2125
- this.logger.log(`[${commandId}] - open() invoked with target ${target} ${context ? `and contextType ${context.type}` : ""}`);
3397
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.log(`[${commandId}] - open() invoked with target ${target} ${context ? `and contextType ${context.type}` : ""}`);
2126
3398
  const name = typeof target === "object" ? target.appId : target;
2127
3399
  const app = this.glueController.getApplication(name);
2128
3400
  if (!app) {
@@ -2130,13 +3402,13 @@
2130
3402
  }
2131
3403
  if (context) {
2132
3404
  yield this.glueEventsController.initializeCollaborateMethod();
2133
- this.logger.info(`[${commandId}] - opening app ${app} with startup context`);
3405
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - opening app ${app} with startup context`);
2134
3406
  return this.openAppWithContext(app, context);
2135
3407
  }
2136
3408
  try {
2137
- this.logger.info(`[${commandId}] - opening app ${app}`);
3409
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.info(`[${commandId}] - opening app ${app}`);
2138
3410
  const glueInst = yield app.start();
2139
- this.logger.info(`[${commandId}] - instance with id ${glueInst.id} started`);
3411
+ (_d = this.logger) === null || _d === void 0 ? void 0 : _d.info(`[${commandId}] - instance with id ${glueInst.id} started`);
2140
3412
  return this.parseGlueInstToAppIdentifier(glueInst);
2141
3413
  }
2142
3414
  catch (error) {
@@ -2145,9 +3417,10 @@
2145
3417
  });
2146
3418
  }
2147
3419
  findInstances({ commandId, appIdentifier }) {
3420
+ var _a, _b;
2148
3421
  return __awaiter(this, void 0, void 0, function* () {
2149
3422
  yield this.glueController.gluePromise;
2150
- this.logger.info(`[${commandId}] - findInstances() invoked with appIdentifier ${appIdentifier}`);
3423
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - findInstances() invoked with appIdentifier ${appIdentifier}`);
2151
3424
  const { appId } = appIdentifier;
2152
3425
  const app = this.glueController.getApplication(appId);
2153
3426
  if (!app) {
@@ -2155,41 +3428,44 @@
2155
3428
  }
2156
3429
  const glueInstances = this.glueController.getApplicationInstances(appId);
2157
3430
  const fdc3Instances = glueInstances.map(glueInst => this.parseGlueInstToAppIdentifier(glueInst));
2158
- this.logger.info(`[${commandId}] - ids of opened instances for appIdentifier ${appIdentifier}: ${JSON.stringify(fdc3Instances.map(inst => inst.instanceId))}`);
3431
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - ids of opened instances for appIdentifier ${appIdentifier}: ${JSON.stringify(fdc3Instances.map(inst => inst.instanceId))}`);
2159
3432
  return fdc3Instances;
2160
3433
  });
2161
3434
  }
2162
3435
  getAppMetadata({ commandId, appIdentifier }) {
3436
+ var _a, _b, _c;
2163
3437
  return __awaiter(this, void 0, void 0, function* () {
2164
3438
  yield this.glueController.gluePromise;
2165
- this.logger.info(`[${commandId}] - getAppMetadata() invoked with appIdentifier ${appIdentifier}`);
3439
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - getAppMetadata() invoked with appIdentifier ${appIdentifier}`);
2166
3440
  const { appId, instanceId } = appIdentifier;
2167
3441
  const app = this.glueController.getApplication(appId);
2168
3442
  if (!app) {
2169
3443
  throw { message: OpenError.AppNotFound, reason: `Cannot find application with appId: ${appId}` };
2170
3444
  }
2171
3445
  if (!instanceId) {
2172
- this.logger.info(`[${commandId}] - no opened instances found. Parsing app ${app}`);
3446
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - no opened instances found. Parsing app ${app}`);
2173
3447
  return this.parseGlueAppToAppMetadata(app);
2174
3448
  }
2175
3449
  const instance = this.glueController.getAppInstanceById(instanceId);
2176
3450
  const appMetadata = this.parseGlueAppToAppMetadata(app, instance);
2177
- this.logger.info(`[${commandId}] - found app metadata: ${appMetadata}`);
3451
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.info(`[${commandId}] - found app metadata: ${appMetadata}`);
2178
3452
  return appMetadata;
2179
3453
  });
2180
3454
  }
2181
3455
  getInfo({ commandId }) {
3456
+ var _a;
2182
3457
  return __awaiter(this, void 0, void 0, function* () {
2183
3458
  yield this.glueController.gluePromise;
2184
- this.logger.info(`${commandId} - getInfo() invoked`);
3459
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`${commandId} - getInfo() invoked`);
2185
3460
  const appMetadata = yield this.getCurrentAppMetadata();
2186
3461
  return {
2187
3462
  provider: "io.Connect",
2188
3463
  providerVersion: version,
2189
- fdc3Version: "2.0",
3464
+ fdc3Version: "2.1",
2190
3465
  optionalFeatures: {
2191
3466
  OriginatingAppMetadata: true,
2192
- UserChannelMembershipAPIs: true
3467
+ UserChannelMembershipAPIs: true,
3468
+ DesktopAgentBridging: false
2193
3469
  },
2194
3470
  appMetadata
2195
3471
  };
@@ -2313,22 +3589,23 @@
2313
3589
  });
2314
3590
  }
2315
3591
  addContextListener({ commandId, handler, contextType, channelId }) {
2316
- var _a;
3592
+ var _a, _b, _c;
2317
3593
  return __awaiter(this, void 0, void 0, function* () {
2318
3594
  yield this.initDonePromise;
2319
- this.logger.info(`[${commandId}] - addContextListener() invoked for contextType ${contextType} and channelId ${channelId}`);
3595
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - addContextListener() invoked for contextType ${contextType} and channelId ${channelId}`);
2320
3596
  if (this.invokeContextHandlerWithStartupContext && !channelId) {
2321
- this.logger.info(`[${commandId}] - trying to invoke context handler with window context`);
2322
- this.handleWindowContextOnOpening(commandId, handler, contextType).catch((err) => this.logger.warn(`[${commandId}] - ${err}`));
3597
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - trying to invoke context handler with window context`);
3598
+ this.handleWindowContextOnOpening(commandId, handler, contextType).catch((err) => { var _a; return (_a = this.logger) === null || _a === void 0 ? void 0 : _a.warn(`[${commandId}] - ${err}`); });
2323
3599
  }
2324
- const channelIdToSubscribeTo = channelId || ((_a = this.channelsStateStore.currentChannel) === null || _a === void 0 ? void 0 : _a.id);
3600
+ const channelIdToSubscribeTo = channelId || ((_c = this.channelsStateStore.currentChannel) === null || _c === void 0 ? void 0 : _c.id);
2325
3601
  return this.addContextListenerByChannelId({ commandId, handler, invokedOnChannelModel: !!channelId, channelId: channelIdToSubscribeTo, contextType });
2326
3602
  });
2327
3603
  }
2328
3604
  broadcast(commandId, context, channelId) {
3605
+ var _a;
2329
3606
  return __awaiter(this, void 0, void 0, function* () {
2330
3607
  yield this.initDonePromise;
2331
- this.logger.info(`[${commandId}] - broadcast() invoked with contextType ${context.type} and channelId ${channelId}`);
3608
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - broadcast() invoked with contextType ${context.type} and channelId ${channelId}`);
2332
3609
  const canBroadcast = this.isBroadcastPermitted(commandId, channelId);
2333
3610
  if (!canBroadcast) {
2334
3611
  return;
@@ -2338,16 +3615,18 @@
2338
3615
  });
2339
3616
  }
2340
3617
  getUserChannels(commandId) {
3618
+ var _a;
2341
3619
  return __awaiter(this, void 0, void 0, function* () {
2342
3620
  yield this.initDonePromise;
2343
- this.logger.info(`[${commandId}] - getUserChannels() invoked`);
3621
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - getUserChannels() invoked`);
2344
3622
  return Object.values(this.channelsStateStore.userChannels);
2345
3623
  });
2346
3624
  }
2347
3625
  getOrCreateChannel({ commandId, channelId }) {
3626
+ var _a;
2348
3627
  return __awaiter(this, void 0, void 0, function* () {
2349
3628
  yield this.initDonePromise;
2350
- this.logger.info(`[${commandId}] - getOrCreateChannel() invoked for channel with id ${channelId}`);
3629
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - getOrCreateChannel() invoked for channel with id ${channelId}`);
2351
3630
  const isUserChannel = this.isUserChannel(channelId);
2352
3631
  if (isUserChannel) {
2353
3632
  throw { message: ChannelError.AccessDenied, reason: "There's an already existing system channel with passed id. Retrieve it using fdc3.getSystemChannels() or create a new app channel with a different id" };
@@ -2360,9 +3639,10 @@
2360
3639
  });
2361
3640
  }
2362
3641
  joinUserChannel({ commandId, channelId }) {
3642
+ var _a, _b;
2363
3643
  return __awaiter(this, void 0, void 0, function* () {
2364
3644
  yield this.initDonePromise;
2365
- this.logger.info(`[${commandId}] - joinUserChannel() invoked for channel with id ${channelId}`);
3645
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - joinUserChannel() invoked for channel with id ${channelId}`);
2366
3646
  const isAppChannel = this.doesAppChannelExist(channelId);
2367
3647
  if (isAppChannel) {
2368
3648
  throw { message: ChannelError.AccessDenied, reason: "Cannot join an app channel" };
@@ -2373,53 +3653,56 @@
2373
3653
  }
2374
3654
  const glueChannelName = this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId);
2375
3655
  this.channelsStateStore.currentChannel = channelToJoin;
2376
- this.logger.info(`[${commandId}] - joining fdc3 user channel with id ${channelId} (underlying glue channel: ${glueChannelName})`);
3656
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - joining fdc3 user channel with id ${channelId} (underlying glue channel: ${glueChannelName})`);
2377
3657
  yield this.glueController.joinChannel(glueChannelName);
2378
3658
  });
2379
3659
  }
2380
3660
  getCurrentChannel(commandId) {
3661
+ var _a;
2381
3662
  return __awaiter(this, void 0, void 0, function* () {
2382
3663
  yield this.initDonePromise;
2383
- this.logger.info(`[${commandId}] - getCurrentChannel() invoked`);
3664
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - getCurrentChannel() invoked`);
2384
3665
  return this.channelsStateStore.currentChannel;
2385
3666
  });
2386
3667
  }
2387
3668
  leaveCurrentChannel(commandId) {
3669
+ var _a, _b, _c;
2388
3670
  return __awaiter(this, void 0, void 0, function* () {
2389
3671
  yield this.initDonePromise;
2390
- this.logger.info(`[${commandId}] - leaveCurrentChannel() invoked`);
3672
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - leaveCurrentChannel() invoked`);
2391
3673
  if (!this.channelsStateStore.currentChannel) {
2392
- this.logger.info(`[${commandId}] - no channel to leave`);
3674
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - no channel to leave`);
2393
3675
  return;
2394
3676
  }
2395
3677
  yield this.glueController.leaveChannel();
2396
3678
  this.channelsStateStore.currentChannel = null;
2397
- this.logger.info(`[${commandId}] - current channel is left. unsubscribing from all listeners`);
3679
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.info(`[${commandId}] - current channel is left. unsubscribing from all listeners`);
2398
3680
  });
2399
3681
  }
2400
3682
  getContextForChannel({ commandId, channelId, contextType }) {
3683
+ var _a, _b, _c, _d, _e;
2401
3684
  return __awaiter(this, void 0, void 0, function* () {
2402
3685
  yield this.initDonePromise;
2403
- this.logger.info(`[${commandId}] - getContextForChannel() invoked for channel with id ${channelId}`);
3686
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - getContextForChannel() invoked for channel with id ${channelId}`);
2404
3687
  const isUserChannel = this.isUserChannel(channelId);
2405
3688
  if (!contextType) {
2406
- this.logger.info(`[${commandId}] - retrieving latest context broadcasted on channel with id ${channelId}`);
3689
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - retrieving latest context broadcasted on channel with id ${channelId}`);
2407
3690
  let context;
2408
3691
  if (isUserChannel) {
2409
3692
  const glueChannelName = this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId);
2410
3693
  const glueChannelWithPrefix = this.channelsParser.mapChannelNameToContextName(glueChannelName);
2411
- this.logger.info(`[${commandId}] - getting context for user channel with id ${channelId} (underlying glue channel ${glueChannelName})`);
3694
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.info(`[${commandId}] - getting context for user channel with id ${channelId} (underlying glue channel ${glueChannelName})`);
2412
3695
  context = yield this.glueController.getContext(glueChannelWithPrefix);
2413
3696
  }
2414
3697
  else {
2415
- this.logger.info(`[${commandId}] - getting context for app channel with id ${channelId}`);
3698
+ (_d = this.logger) === null || _d === void 0 ? void 0 : _d.info(`[${commandId}] - getting context for app channel with id ${channelId}`);
2416
3699
  context = yield this.glueController.getContext(channelId);
2417
3700
  }
2418
3701
  return context.latest_fdc3_type
2419
3702
  ? this.channelsParser.parseContextsDataToInitialFDC3Data(context)
2420
3703
  : null;
2421
3704
  }
2422
- this.logger.info(`[${commandId}] Retrieving latest context of type ${contextType} broadcasted on ${isUserChannel ? "user" : "app"} channel with id ${channelId}`);
3705
+ (_e = this.logger) === null || _e === void 0 ? void 0 : _e.info(`[${commandId}] Retrieving latest context of type ${contextType} broadcasted on ${isUserChannel ? "user" : "app"} channel with id ${channelId}`);
2423
3706
  const parsedType = this.channelsParser.mapFDC3TypeToChannelsDelimiter(contextType);
2424
3707
  const { data } = isUserChannel
2425
3708
  ? yield this.glueController.getChannel(this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId))
@@ -2430,9 +3713,10 @@
2430
3713
  });
2431
3714
  }
2432
3715
  createPrivateChannel(commandId) {
3716
+ var _a;
2433
3717
  return __awaiter(this, void 0, void 0, function* () {
2434
3718
  yield this.initDonePromise;
2435
- this.logger.info(`[${commandId}] - createPrivateChannel() invoked`);
3719
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - createPrivateChannel() invoked`);
2436
3720
  const channelId = `${PrivateChannelPrefix}${nanoid()}`;
2437
3721
  yield this.glueEventsController.initializeCollaborateMethod();
2438
3722
  const pc = this.buildPrivateChannel(channelId, commandId, true);
@@ -2456,26 +3740,30 @@
2456
3740
  return this.glueController.getMyInteropInstance();
2457
3741
  }
2458
3742
  addClientToPrivateChannel(commandId, channelId, clientId) {
3743
+ var _a;
2459
3744
  return __awaiter(this, void 0, void 0, function* () {
2460
- this.logger.info(`[${commandId}] - client with id ${clientId} added to private channel with id ${channelId}`);
3745
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - client with id ${clientId} added to private channel with id ${channelId}`);
2461
3746
  yield this.glueController.updateContext(channelId, { clientId });
2462
3747
  });
2463
3748
  }
2464
3749
  isPrivateChannelDisconnected({ commandId, channelId }) {
3750
+ var _a;
2465
3751
  return __awaiter(this, void 0, void 0, function* () {
2466
- this.logger.info(`[${commandId}] - checking if private channel with id ${channelId} is disconnected`);
3752
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - checking if private channel with id ${channelId} is disconnected`);
2467
3753
  const context = yield this.glueController.getContext(channelId);
2468
3754
  return !!context.disconnected;
2469
3755
  });
2470
3756
  }
2471
3757
  subscribeOnInstanceStop(channelId, handler, commandId) {
2472
- this.logger.info(`[${commandId}] - subscribing onInstanceStopped callback for channel with id ${channelId}`);
3758
+ var _a;
3759
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - subscribing onInstanceStopped callback for channel with id ${channelId}`);
2473
3760
  return this.glueController.registerOnInstanceStopped(handler.bind(this));
2474
3761
  }
2475
3762
  buildPrivateChannel(channelId, commandId, isCreator) {
3763
+ var _a;
2476
3764
  const logger = this.glueController.initSubLogger(channelId);
2477
3765
  const channel = this.buildChannel(ChannelTypes.Private, { id: channelId, logger, isCreator });
2478
- this.logger.info(`[${commandId}] - private channel with id ${channelId} created. Adding it to the store`);
3766
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - private channel with id ${channelId} created. Adding it to the store`);
2479
3767
  this.channelsStateStore.addPrivateChannel(channel);
2480
3768
  return channel;
2481
3769
  }
@@ -2513,70 +3801,73 @@
2513
3801
  });
2514
3802
  }
2515
3803
  isBroadcastPermitted(commandId, channelId) {
3804
+ var _a, _b;
2516
3805
  if (channelId) {
2517
3806
  return true;
2518
3807
  }
2519
3808
  if (!this.channelsStateStore.currentChannel) {
2520
- this.logger.info(`[${commandId}] - invocation of broadcast ignored - no channel to broadcast to`);
3809
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - invocation of broadcast ignored - no channel to broadcast to`);
2521
3810
  console.error("You need to join a user channel in order to broadcast");
2522
3811
  return false;
2523
3812
  }
2524
3813
  if (this.channelsStateStore.currentChannel.type === ChannelTypes.App) {
2525
- this.logger.info(`[${commandId}] - invocation of broadcast ignored - cannot broadcast on app channel directly`);
3814
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - invocation of broadcast ignored - cannot broadcast on app channel directly`);
2526
3815
  console.error("You can't broadcast to an app channel directly - use channel's broadcast method instead");
2527
3816
  return false;
2528
3817
  }
2529
3818
  return true;
2530
3819
  }
2531
3820
  handleWindowContextOnOpening(commandId, handler, contextType) {
3821
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
2532
3822
  return __awaiter(this, void 0, void 0, function* () {
2533
3823
  const myWindow = this.glueController.getMyWindow();
2534
3824
  if (!myWindow) {
2535
- this.logger.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
3825
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
2536
3826
  this.invokeContextHandlerWithStartupContext = false;
2537
3827
  return;
2538
3828
  }
2539
3829
  const windowContext = yield myWindow.getContext();
2540
3830
  if (!windowContext) {
2541
- this.logger.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
3831
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
2542
3832
  this.invokeContextHandlerWithStartupContext = false;
2543
3833
  return;
2544
3834
  }
2545
3835
  if (!isValidNonEmptyObject(windowContext) || !windowContext.fdc3) {
2546
- this.logger.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
3836
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
2547
3837
  this.invokeContextHandlerWithStartupContext = false;
2548
3838
  return;
2549
3839
  }
2550
3840
  yield this.glueEventsController.initializeCollaborateMethod();
2551
3841
  FDC3StartupContextDecoder.runWithException(windowContext);
2552
3842
  const { fdc3 } = windowContext;
2553
- this.logger.trace(`[${commandId}] - received FDC3 startup context from ${JSON.stringify(fdc3.openApp)} for contextType ${fdc3.context.contextType}`);
3843
+ (_d = this.logger) === null || _d === void 0 ? void 0 : _d.trace(`[${commandId}] - received FDC3 startup context from ${JSON.stringify(fdc3.openApp)} for contextType ${fdc3.context.contextType}`);
2554
3844
  const isSameContextType = contextType ? fdc3.context.contextType === contextType : true;
2555
3845
  if (!isSameContextType) {
2556
- this.logger.info(`[${commandId}] - addContextListener handler won't be invoked for contextType ${contextType} for startup context with type: ${fdc3.context.contextType}`);
3846
+ (_e = this.logger) === null || _e === void 0 ? void 0 : _e.info(`[${commandId}] - addContextListener handler won't be invoked for contextType ${contextType} for startup context with type: ${fdc3.context.contextType}`);
2557
3847
  return;
2558
3848
  }
2559
- this.logger.info(`[${commandId}] - invoking addContextListener handler with startup context with type ${fdc3.context.contextType}`);
3849
+ (_f = this.logger) === null || _f === void 0 ? void 0 : _f.info(`[${commandId}] - invoking addContextListener handler with startup context with type ${fdc3.context.contextType}`);
2560
3850
  try {
2561
3851
  handler(fdc3.context.payload, { source: fdc3.openApp });
2562
3852
  }
2563
3853
  catch (error) {
2564
- this.logger.error(typeof error === "string" ? error : error.message ? JSON.stringify(error.message) : JSON.stringify(error));
3854
+ (_g = this.logger) === null || _g === void 0 ? void 0 : _g.error(typeof error === "string" ? error : error.message ? JSON.stringify(error.message) : JSON.stringify(error));
2565
3855
  }
2566
3856
  this.invokeContextHandlerWithStartupContext = false;
2567
- this.logger.trace(`[${commandId}] - invoking response method to with target ${JSON.stringify(fdc3.openApp)}`);
3857
+ (_h = this.logger) === null || _h === void 0 ? void 0 : _h.trace(`[${commandId}] - invoking response method to with target ${JSON.stringify(fdc3.openApp)}`);
2568
3858
  yield this.invokeSystemMethod({ action: "startupContextOpened", correlationId: fdc3.collaborationId }, fdc3.openApp.instanceId);
2569
- this.logger.trace(`[${commandId}] - system method invocation success for 'startupContextOpened' heard`);
3859
+ (_j = this.logger) === null || _j === void 0 ? void 0 : _j.trace(`[${commandId}] - system method invocation success for 'startupContextOpened' heard`);
2570
3860
  });
2571
3861
  }
2572
3862
  getOrCreateAppChannel(commandId, channelId) {
3863
+ var _a, _b;
2573
3864
  return __awaiter(this, void 0, void 0, function* () {
2574
3865
  const exists = this.doesAppChannelExist(channelId);
2575
3866
  if (!exists) {
2576
- this.logger.info(`[${commandId}] - app channel with id ${channelId} does not exist. Creating one`);
3867
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - app channel with id ${channelId} does not exist. Creating one`);
2577
3868
  yield this.glueController.updateContext(channelId, {});
2578
3869
  }
2579
- this.logger.info(`[${commandId}] - returning app channel with id ${channelId}`);
3870
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - returning app channel with id ${channelId}`);
2580
3871
  const logger = this.glueController.initSubLogger(`app.channel.${channelId}`);
2581
3872
  return this.buildChannel(ChannelTypes.App, { id: channelId, logger });
2582
3873
  });
@@ -2591,22 +3882,24 @@
2591
3882
  return !!this.channelsStateStore.userChannels[channelId];
2592
3883
  }
2593
3884
  broadcastByChannelId(commandId, channelId, context) {
3885
+ var _a, _b;
2594
3886
  return __awaiter(this, void 0, void 0, function* () {
2595
3887
  const isUserChannel = this.isUserChannel(channelId);
2596
3888
  if (!isUserChannel) {
2597
- this.logger.info(`[${commandId}] - broadcasting on app channel with id ${channelId}`);
3889
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - broadcasting on app channel with id ${channelId}`);
2598
3890
  return this.glueController.updateContextWithLatestFdc3Type(channelId, context);
2599
3891
  }
2600
3892
  const glueChannelName = this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId);
2601
- this.logger.info(`[${commandId}] - broadcasting on fdc3 user channel with id ${channelId} (underlying glue channel: ${glueChannelName})`);
3893
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - broadcasting on fdc3 user channel with id ${channelId} (underlying glue channel: ${glueChannelName})`);
2602
3894
  return this.glueController.channelsUpdate(glueChannelName, context);
2603
3895
  });
2604
3896
  }
2605
3897
  addContextListenerByChannelId({ commandId, channelId, handler, contextType, invokedOnChannelModel }) {
3898
+ var _a, _b;
2606
3899
  return __awaiter(this, void 0, void 0, function* () {
2607
3900
  const subHandler = parseContextHandler(handler, contextType);
2608
3901
  if (!channelId) {
2609
- this.logger.info(`[${commandId}] - Creating a channel subscription using glue.channels.subscribe`);
3902
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - Creating a channel subscription using glue.channels.subscribe`);
2610
3903
  const unsubscribe = this.glueController.channelsSubscribe(subHandler, contextType);
2611
3904
  return { unsubscribe };
2612
3905
  }
@@ -2615,11 +3908,12 @@
2615
3908
  return this.addContextListenerOnUserChannel({ commandId, channelId, handler: subHandler, contextType, invokedOnChannelModel });
2616
3909
  }
2617
3910
  if (channelType === ChannelTypes.App) {
2618
- this.logger.info(`[${commandId}] - subscribing for fdc3 app channel with id ${channelId} (underlying glue context with same name)`);
3911
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - subscribing for fdc3 app channel with id ${channelId} (underlying glue context with same name)`);
2619
3912
  const unsubscribe = yield this.glueController.contextsSubscribe(channelId, subHandler);
2620
3913
  return {
2621
3914
  unsubscribe: () => {
2622
- this.logger.info(`[${commandId}] - invoking unsubscribe for app channel with id ${channelId}`);
3915
+ var _a;
3916
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - invoking unsubscribe for app channel with id ${channelId}`);
2623
3917
  unsubscribe();
2624
3918
  }
2625
3919
  };
@@ -2628,20 +3922,22 @@
2628
3922
  });
2629
3923
  }
2630
3924
  addContextListenerOnUserChannel({ commandId, channelId, handler, invokedOnChannelModel, contextType }) {
3925
+ var _a, _b;
2631
3926
  return __awaiter(this, void 0, void 0, function* () {
2632
3927
  let unsubscribe;
2633
3928
  if (invokedOnChannelModel) {
2634
3929
  const contextToSubscribeTo = this.channelsParser.mapChannelNameToContextName(this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId));
2635
- this.logger.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
3930
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
2636
3931
  unsubscribe = yield this.glueController.contextsSubscribe(contextToSubscribeTo, handler);
2637
3932
  }
2638
3933
  else {
2639
- this.logger.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
3934
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
2640
3935
  unsubscribe = this.glueController.channelsSubscribe(handler, contextType);
2641
3936
  }
2642
3937
  return {
2643
3938
  unsubscribe: () => {
2644
- this.logger.info(`[${commandId}] - invoking unsubscribe for fdc3 user channel with id ${channelId}`);
3939
+ var _a;
3940
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(`[${commandId}] - invoking unsubscribe for fdc3 user channel with id ${channelId}`);
2645
3941
  unsubscribe();
2646
3942
  }
2647
3943
  };
@@ -2919,7 +4215,7 @@
2919
4215
  return __awaiter(this, void 0, void 0, function* () {
2920
4216
  this.setCollaborator(collaborator, commandId);
2921
4217
  yield Promise.all(this.myListenerTypesBeforeBound.map((contextType) => {
2922
- var _a;
4218
+ var _a, _b;
2923
4219
  const listenerAddedArgs = {
2924
4220
  action: "addedContextListenerOnPrivateChannel",
2925
4221
  correlationId: this.id,
@@ -2928,25 +4224,28 @@
2928
4224
  contextType: contextType || undefined
2929
4225
  }
2930
4226
  };
2931
- this.logger.trace(`[${commandId}] - announcing ${"addedContextListenerOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
2932
- return this.channelsController.invokeSystemMethod(listenerAddedArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
2933
- })).catch((err) => this.logger.error(err));
4227
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.trace(`[${commandId}] - announcing ${"addedContextListenerOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
4228
+ return this.channelsController.invokeSystemMethod(listenerAddedArgs, (_b = this.collaborator) === null || _b === void 0 ? void 0 : _b.instanceId);
4229
+ })).catch((err) => { var _a; return (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(err); });
2934
4230
  });
2935
4231
  }
2936
4232
  handleCollaboratorBroadcast(context, metadata, commandId) {
2937
- this.logger.trace(`[${commandId}] - heard context with type ${context.type} broadcasted on the channel`);
4233
+ var _a, _b;
4234
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.trace(`[${commandId}] - heard context with type ${context.type} broadcasted on the channel`);
2938
4235
  this.lastBroadcastedContextType = context.type;
2939
4236
  this.broadcastedContexts[context.type] = { context, metadata };
2940
- this.logger.trace(`[${commandId}] - invoking all context listeners`);
4237
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.trace(`[${commandId}] - invoking all context listeners`);
2941
4238
  this.registry.execute(PrivateChannelEventMethods.ListenerAdded, context, metadata);
2942
4239
  }
2943
4240
  handleCollaboratorAddContextListener(contextType, commandId) {
2944
- this.logger.trace(`[${commandId}] - heard collaborator added context listener for type ${contextType}`);
4241
+ var _a;
4242
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.trace(`[${commandId}] - heard collaborator added context listener for type ${contextType}`);
2945
4243
  this.collaboratorListenerTypes.push(contextType);
2946
4244
  this.registry.execute(PrivateChannelEventMethods.OnAddContextListener, contextType);
2947
4245
  }
2948
4246
  handleCollaboratorRemovedListener(contextType, commandId) {
2949
- this.logger.trace(`[${commandId}] - heard collaborator removed context listener with type ${contextType}`);
4247
+ var _a;
4248
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.trace(`[${commandId}] - heard collaborator removed context listener with type ${contextType}`);
2950
4249
  const index = this.collaboratorListenerTypes.indexOf(contextType);
2951
4250
  this.collaboratorListenerTypes.splice(index, 1);
2952
4251
  this.registry.execute(PrivateChannelEventMethods.OnUnsubscribe, contextType);
@@ -2957,6 +4256,7 @@
2957
4256
  this.registry.execute(PrivateChannelEventMethods.OnDisconnect);
2958
4257
  }
2959
4258
  announceJoin(targetInstance, commandId) {
4259
+ var _a, _b;
2960
4260
  return __awaiter(this, void 0, void 0, function* () {
2961
4261
  const joinChannelArgs = {
2962
4262
  action: "joinPrivateChannel",
@@ -2965,18 +4265,21 @@
2965
4265
  channelId: this.id
2966
4266
  }
2967
4267
  };
2968
- this.logger.trace(`[${commandId}] - announcing ${"joinPrivateChannel"} to target instance with id ${JSON.stringify(targetInstance)}`);
4268
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.trace(`[${commandId}] - announcing ${"joinPrivateChannel"} to target instance with id ${JSON.stringify(targetInstance)}`);
2969
4269
  yield this.channelsController.invokeSystemMethod(joinChannelArgs, targetInstance);
2970
- this.logger.trace(`[${commandId}] - collaborator received ${"joinPrivateChannel"} action`);
4270
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.trace(`[${commandId}] - collaborator received ${"joinPrivateChannel"} action`);
2971
4271
  });
2972
4272
  }
2973
4273
  broadcast(context) {
2974
- var _a;
4274
+ var _a, _b, _c;
2975
4275
  return __awaiter(this, void 0, void 0, function* () {
4276
+ const contextDecoderResult = contextDecoder.run(context);
4277
+ if (!contextDecoderResult.ok) {
4278
+ throw new Error(ChannelError.MalformedContext);
4279
+ }
2976
4280
  const commandId = generateCommandId();
2977
4281
  this.ensureAlive(commandId);
2978
4282
  this.ensureBound(commandId, "broadcast");
2979
- contextDecoder.runWithException(context);
2980
4283
  this.lastBroadcastedContextType = context.type;
2981
4284
  this.broadcastedContexts[context.type] = { context, metadata: this.myAppMetadata };
2982
4285
  const broadcastArgs = {
@@ -2988,27 +4291,29 @@
2988
4291
  payload: context
2989
4292
  }
2990
4293
  };
2991
- this.logger.trace(`[${commandId}] - announcing ${"publishOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
2992
- yield this.channelsController.invokeSystemMethod(broadcastArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
2993
- this.logger.trace(`[${commandId}] - collaborator received context for action ${"publishOnPrivateChannel"}`);
4294
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.trace(`[${commandId}] - announcing ${"publishOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
4295
+ yield this.channelsController.invokeSystemMethod(broadcastArgs, (_b = this.collaborator) === null || _b === void 0 ? void 0 : _b.instanceId);
4296
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.trace(`[${commandId}] - collaborator received context for action ${"publishOnPrivateChannel"}`);
2994
4297
  });
2995
4298
  }
2996
4299
  getCurrentContext(contextType) {
4300
+ var _a, _b;
2997
4301
  return __awaiter(this, void 0, void 0, function* () {
2998
4302
  const commandId = generateCommandId();
2999
4303
  this.ensureAlive(commandId);
3000
- this.logger.trace(`[${commandId}] - getCurrentContext invoked ${contextType ? `with contextType ${contextType}` : ""}`);
4304
+ const contextTypeMessage = contextType ? ` with contextType ${contextType}` : "";
4305
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.trace(`[${commandId}] - getCurrentContext invoked ${contextTypeMessage}`);
3001
4306
  optionalNonEmptyStringDecoder.runWithException(contextType);
3002
4307
  if (!contextType && !this.lastBroadcastedContextType) {
3003
4308
  return null;
3004
4309
  }
3005
4310
  const searchedType = contextType || this.lastBroadcastedContextType;
3006
- this.logger.trace(`[${commandId}] - Returning context with type ${searchedType}`);
4311
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.trace(`[${commandId}] - Returning context with type ${searchedType}`);
3007
4312
  return this.broadcastedContexts[searchedType].context;
3008
4313
  });
3009
4314
  }
3010
4315
  addContextListener(contextType, handler) {
3011
- var _a;
4316
+ var _a, _b, _c, _d;
3012
4317
  return __awaiter(this, void 0, void 0, function* () {
3013
4318
  const commandId = generateCommandId();
3014
4319
  this.ensureAlive(commandId);
@@ -3016,7 +4321,7 @@
3016
4321
  if (typeof handler !== "function") {
3017
4322
  throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
3018
4323
  }
3019
- this.logger.trace(`[${commandId}] - adding subscription for broadcasted contexts with type: ${contextType}`);
4324
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.trace(`[${commandId}] - adding subscription for broadcasted contexts with type: ${contextType}`);
3020
4325
  const subHandler = (data, metadata) => {
3021
4326
  if (contextType) {
3022
4327
  if (data.type === contextType) {
@@ -3038,9 +4343,9 @@
3038
4343
  contextType: contextType || undefined
3039
4344
  }
3040
4345
  };
3041
- this.logger.trace(`[${commandId}] - announcing ${"addedContextListenerOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
3042
- yield this.channelsController.invokeSystemMethod(listenerAddedArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3043
- this.logger.trace(`[${commandId}] - collaborator received action ${"addedContextListenerOnPrivateChannel"}`);
4346
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.trace(`[${commandId}] - announcing ${"addedContextListenerOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
4347
+ yield this.channelsController.invokeSystemMethod(listenerAddedArgs, (_c = this.collaborator) === null || _c === void 0 ? void 0 : _c.instanceId);
4348
+ (_d = this.logger) === null || _d === void 0 ? void 0 : _d.trace(`[${commandId}] - collaborator received action ${"addedContextListenerOnPrivateChannel"}`);
3044
4349
  }
3045
4350
  else {
3046
4351
  this.myListenerTypesBeforeBound.push(contextType);
@@ -3063,7 +4368,7 @@
3063
4368
  }
3064
4369
  getAddContextListenerUnsub(unsub, contextType, commandId) {
3065
4370
  return () => __awaiter(this, void 0, void 0, function* () {
3066
- var _a;
4371
+ var _a, _b, _c;
3067
4372
  unsub();
3068
4373
  if (!this.collaborator) {
3069
4374
  const index = this.myListenerTypesBeforeBound.indexOf(contextType);
@@ -3078,9 +4383,9 @@
3078
4383
  contextType: contextType || undefined
3079
4384
  }
3080
4385
  };
3081
- this.logger.trace(`[${commandId}] - announcing unsubscribe from context listener for type ${contextType}`);
3082
- yield this.channelsController.invokeSystemMethod(unsubArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3083
- this.logger.trace(`[${commandId}] - collaborator heard ${"removedContextListenerOnPrivateChannel"}`);
4386
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.trace(`[${commandId}] - announcing unsubscribe from context listener for type ${contextType}`);
4387
+ yield this.channelsController.invokeSystemMethod(unsubArgs, (_b = this.collaborator) === null || _b === void 0 ? void 0 : _b.instanceId);
4388
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.trace(`[${commandId}] - collaborator heard ${"removedContextListenerOnPrivateChannel"}`);
3084
4389
  });
3085
4390
  }
3086
4391
  onAddContextListener(handler) {
@@ -3111,7 +4416,7 @@
3111
4416
  return AsyncListener(unsub);
3112
4417
  }
3113
4418
  disconnect() {
3114
- var _a;
4419
+ var _a, _b, _c, _d;
3115
4420
  return __awaiter(this, void 0, void 0, function* () {
3116
4421
  const commandId = generateCommandId();
3117
4422
  if (this.isCreator && !this.collaborator) {
@@ -3120,9 +4425,9 @@
3120
4425
  }
3121
4426
  this.ensureAlive(commandId);
3122
4427
  this.ensureBound(commandId, "disconnect");
3123
- this.logger.trace(`[${commandId}] - disconnect invoked`);
4428
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.trace(`[${commandId}] - disconnect invoked`);
3124
4429
  this.disconnected = true;
3125
- this.logger.trace(`[${commandId}] - announcing ${"disconnectedFromPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
4430
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.trace(`[${commandId}] - announcing ${"disconnectedFromPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
3126
4431
  const disconnectArgs = {
3127
4432
  action: "disconnectedFromPrivateChannel",
3128
4433
  correlationId: this.id,
@@ -3131,27 +4436,29 @@
3131
4436
  }
3132
4437
  };
3133
4438
  this.channelsController.removePrivateChannelFromStoreById(this.id);
3134
- yield this.channelsController.invokeSystemMethod(disconnectArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3135
- this.logger.trace(`[${commandId}] - collaborator received action ${"disconnectedFromPrivateChannel"}`);
4439
+ yield this.channelsController.invokeSystemMethod(disconnectArgs, (_c = this.collaborator) === null || _c === void 0 ? void 0 : _c.instanceId);
4440
+ (_d = this.logger) === null || _d === void 0 ? void 0 : _d.trace(`[${commandId}] - collaborator received action ${"disconnectedFromPrivateChannel"}`);
3136
4441
  if (this.unsubFromInstanceStopped) {
3137
4442
  this.unsubFromInstanceStopped();
3138
4443
  }
3139
4444
  });
3140
4445
  }
3141
4446
  ensureAlive(commandId) {
4447
+ var _a;
3142
4448
  if (!this.disconnected) {
3143
4449
  return;
3144
4450
  }
3145
4451
  const errorMsg = "Channel is disconnected - operation is no longer available";
3146
- this.logger.error(`[${commandId}] - ${errorMsg}`);
4452
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(`[${commandId}] - ${errorMsg}`);
3147
4453
  throw { message: ChannelError.AccessDenied, reason: errorMsg };
3148
4454
  }
3149
4455
  ensureBound(commandId, operation) {
4456
+ var _a;
3150
4457
  if (this.collaborator) {
3151
4458
  return;
3152
4459
  }
3153
4460
  const errorMsg = `There's no collaborator on the other side of the channel - operation ${operation} is unavailable`;
3154
- this.logger.error(`[${commandId}] - ${errorMsg}`);
4461
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(`[${commandId}] - ${errorMsg}`);
3155
4462
  throw { message: ChannelError.AccessDenied, reason: errorMsg };
3156
4463
  }
3157
4464
  subscribeForCollaboratorInstanceStop(commandId) {
@@ -3222,17 +4529,18 @@
3222
4529
  return !!methodsByThisInstance.length;
3223
4530
  }
3224
4531
  handleReceivedAction(eventArgs, instance) {
4532
+ var _a, _b;
3225
4533
  return __awaiter(this, void 0, void 0, function* () {
3226
4534
  const argsDecodeResult = SystemMethodInvocationArgumentDecoder.run(eventArgs);
3227
4535
  if (!argsDecodeResult.ok) {
3228
4536
  throw new Error(`Interop Method ${ioConnectFDC3SystemMethod} invoked with invalid argument object - ${argsDecodeResult.error}`);
3229
4537
  }
3230
4538
  const commandId = generateCommandId();
3231
- this.logger.log(`${commandId} - received system method from instance with id ${instance.instance} for action ${eventArgs.action} with arguments: ${JSON.stringify(eventArgs)}`);
4539
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.log(`${commandId} - received system method from instance with id ${instance.instance} for action ${eventArgs.action} with arguments: ${JSON.stringify(eventArgs)}`);
3232
4540
  const operation = this.actionDictionary[eventArgs.action];
3233
4541
  if (!operation) {
3234
4542
  const errorMsg = `Unsupported private channel action: ${eventArgs.action}`;
3235
- this.logger.error(`[${commandId}] - ${errorMsg}`);
4543
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error(`[${commandId}] - ${errorMsg}`);
3236
4544
  throw new Error(errorMsg);
3237
4545
  }
3238
4546
  yield operation(eventArgs, instance, commandId);
@@ -3245,10 +4553,11 @@
3245
4553
  return this._logger;
3246
4554
  }
3247
4555
  validateAndRetrieveChannel({ action, correlationId }, instance, commandId) {
4556
+ var _a, _b, _c;
3248
4557
  const privateChannel = this.channelsStateStore.getPrivateChannelById(correlationId);
3249
4558
  if (!privateChannel) {
3250
4559
  const errorMsg = `There's no private channel with id ${correlationId}`;
3251
- this.logger.error(`[${commandId}] - ${errorMsg}`);
4560
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(`[${commandId}] - ${errorMsg}`);
3252
4561
  throw new Error(errorMsg);
3253
4562
  }
3254
4563
  const channelCollaborator = privateChannel.getCollaborator();
@@ -3256,26 +4565,27 @@
3256
4565
  return privateChannel;
3257
4566
  }
3258
4567
  if (channelCollaborator && channelCollaborator.instanceId === instance.instance) {
3259
- this.logger.log(`[${commandId}] - request sent from correct collaborator with id ${instance.instance}. Returning channel`);
4568
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.log(`[${commandId}] - request sent from correct collaborator with id ${instance.instance}. Returning channel`);
3260
4569
  return privateChannel;
3261
4570
  }
3262
4571
  const errorMsg = `Cannot proceed with action ${action} - ${channelCollaborator
3263
4572
  ? `private channel ${correlationId} established communication with collaborator with id ${channelCollaborator}`
3264
4573
  : `no collaborator joined private channel with id ${correlationId}`}`;
3265
- this.logger.error(errorMsg);
4574
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.error(errorMsg);
3266
4575
  throw new Error(errorMsg);
3267
4576
  }
3268
4577
  handleJoin(eventArgs, instance, commandId) {
4578
+ var _a;
3269
4579
  return __awaiter(this, void 0, void 0, function* () {
3270
4580
  const collaborator = { appId: instance.application || instance.applicationName, instanceId: instance.instance };
3271
4581
  const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3272
4582
  yield privateChannel.handleCollaboratorJoin(collaborator, commandId);
3273
- this.logger.log(`[${commandId}] - collaborator ${JSON.stringify(collaborator)} set for private channel with id ${eventArgs.correlationId}`);
4583
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.log(`[${commandId}] - collaborator ${JSON.stringify(collaborator)} set for private channel with id ${eventArgs.correlationId}`);
3274
4584
  });
3275
4585
  }
3276
4586
  handlePublish(eventArgs, instance, commandId) {
3277
- var _a, _b;
3278
- this.logger.log(`[${commandId}] - received ${eventArgs.action} action, adding context with type ${(_a = eventArgs.collaborationObject) === null || _a === void 0 ? void 0 : _a.contextType} to the private channel broadcasted contexts`);
4587
+ var _a, _b, _c;
4588
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.log(`[${commandId}] - received ${eventArgs.action} action, adding context with type ${(_b = eventArgs.collaborationObject) === null || _b === void 0 ? void 0 : _b.contextType} to the private channel broadcasted contexts`);
3279
4589
  const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3280
4590
  const metadata = {
3281
4591
  source: {
@@ -3283,33 +4593,35 @@
3283
4593
  instanceId: instance.instance
3284
4594
  }
3285
4595
  };
3286
- privateChannel.handleCollaboratorBroadcast((_b = eventArgs.collaborationObject) === null || _b === void 0 ? void 0 : _b.payload, metadata, commandId);
4596
+ privateChannel.handleCollaboratorBroadcast((_c = eventArgs.collaborationObject) === null || _c === void 0 ? void 0 : _c.payload, metadata, commandId);
3287
4597
  }
3288
4598
  handleContextListenerAdded(eventArgs, instance, commandId) {
3289
- var _a;
3290
- this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onAddContextListener' callbacks`);
4599
+ var _a, _b;
4600
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onAddContextListener' callbacks`);
3291
4601
  const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3292
- privateChannel.handleCollaboratorAddContextListener(((_a = eventArgs.collaborationObject) === null || _a === void 0 ? void 0 : _a.contextType) || null, commandId);
4602
+ privateChannel.handleCollaboratorAddContextListener(((_b = eventArgs.collaborationObject) === null || _b === void 0 ? void 0 : _b.contextType) || null, commandId);
3293
4603
  }
3294
4604
  handleContextListenerRemoved(eventArgs, instance, commandId) {
3295
- var _a;
3296
- this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onUnsubscribe' callbacks`);
4605
+ var _a, _b;
4606
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onUnsubscribe' callbacks`);
3297
4607
  const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3298
- privateChannel.handleCollaboratorRemovedListener(((_a = eventArgs.collaborationObject) === null || _a === void 0 ? void 0 : _a.contextType) || null, commandId);
4608
+ privateChannel.handleCollaboratorRemovedListener(((_b = eventArgs.collaborationObject) === null || _b === void 0 ? void 0 : _b.contextType) || null, commandId);
3299
4609
  }
3300
4610
  handleDisconnect(eventArgs, instance, commandId) {
3301
- this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onDisconnect' callbacks`);
4611
+ var _a;
4612
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onDisconnect' callbacks`);
3302
4613
  const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3303
4614
  privateChannel.handleCollaboratorDisconnect();
3304
4615
  }
3305
4616
  handleStartupContextOpened(eventArgs, instance, commandId) {
3306
- this.logger.log(`[${commandId}] - received ${eventArgs.action} with correlationId: ${eventArgs.correlationId} from instance with id ${instance.instance}`);
4617
+ var _a, _b, _c;
4618
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.log(`[${commandId}] - received ${eventArgs.action} with correlationId: ${eventArgs.correlationId} from instance with id ${instance.instance}`);
3307
4619
  const wrappedPromise = this.appsStateStore.getOpenAppPromise(eventArgs.correlationId);
3308
4620
  if (!wrappedPromise) {
3309
- this.logger.log(`[${commandId}] - there's no open app promise related to guid ${eventArgs.correlationId}`);
4621
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.log(`[${commandId}] - there's no open app promise related to guid ${eventArgs.correlationId}`);
3310
4622
  return;
3311
4623
  }
3312
- this.logger.log(`[${commandId}] - resolving open app promise related to guid ${eventArgs.correlationId} from instance with id ${instance.instance}`);
4624
+ (_c = this.logger) === null || _c === void 0 ? void 0 : _c.log(`[${commandId}] - resolving open app promise related to guid ${eventArgs.correlationId} from instance with id ${instance.instance}`);
3313
4625
  wrappedPromise.resolve();
3314
4626
  }
3315
4627
  }