@interopio/fdc3-web-bridge 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3649 @@
1
+ /* @ts-self-types="./index.d.ts" */
2
+ let urlAlphabet =
3
+ 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
4
+ let nanoid = (size = 21) => {
5
+ let id = '';
6
+ let i = size | 0;
7
+ while (i--) {
8
+ id += urlAlphabet[(Math.random() * 64) | 0];
9
+ }
10
+ return id
11
+ };
12
+
13
+ /**
14
+ * Wraps values in an `Ok` type.
15
+ *
16
+ * Example: `ok(5) // => {ok: true, result: 5}`
17
+ */
18
+ var ok$1 = function (result) { return ({ ok: true, result: result }); };
19
+ /**
20
+ * Wraps errors in an `Err` type.
21
+ *
22
+ * Example: `err('on fire') // => {ok: false, error: 'on fire'}`
23
+ */
24
+ var err$1 = function (error) { return ({ ok: false, error: error }); };
25
+ /**
26
+ * Create a `Promise` that either resolves with the result of `Ok` or rejects
27
+ * with the error of `Err`.
28
+ */
29
+ var asPromise$1 = function (r) {
30
+ return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error);
31
+ };
32
+ /**
33
+ * Unwraps a `Result` and returns either the result of an `Ok`, or
34
+ * `defaultValue`.
35
+ *
36
+ * Example:
37
+ * ```
38
+ * Result.withDefault(5, number().run(json))
39
+ * ```
40
+ *
41
+ * It would be nice if `Decoder` had an instance method that mirrored this
42
+ * function. Such a method would look something like this:
43
+ * ```
44
+ * class Decoder<A> {
45
+ * runWithDefault = (defaultValue: A, json: any): A =>
46
+ * Result.withDefault(defaultValue, this.run(json));
47
+ * }
48
+ *
49
+ * number().runWithDefault(5, json)
50
+ * ```
51
+ * Unfortunately, the type of `defaultValue: A` on the method causes issues
52
+ * with type inference on the `object` decoder in some situations. While these
53
+ * inference issues can be solved by providing the optional type argument for
54
+ * `object`s, the extra trouble and confusion doesn't seem worth it.
55
+ */
56
+ var withDefault$1 = function (defaultValue, r) {
57
+ return r.ok === true ? r.result : defaultValue;
58
+ };
59
+ /**
60
+ * Return the successful result, or throw an error.
61
+ */
62
+ var withException$1 = function (r) {
63
+ if (r.ok === true) {
64
+ return r.result;
65
+ }
66
+ else {
67
+ throw r.error;
68
+ }
69
+ };
70
+ /**
71
+ * Apply `f` to the result of an `Ok`, or pass the error through.
72
+ */
73
+ var map$1 = function (f, r) {
74
+ return r.ok === true ? ok$1(f(r.result)) : r;
75
+ };
76
+ /**
77
+ * Apply `f` to the result of two `Ok`s, or pass an error through. If both
78
+ * `Result`s are errors then the first one is returned.
79
+ */
80
+ var map2$1 = function (f, ar, br) {
81
+ return ar.ok === false ? ar :
82
+ br.ok === false ? br :
83
+ ok$1(f(ar.result, br.result));
84
+ };
85
+ /**
86
+ * Apply `f` to the error of an `Err`, or pass the success through.
87
+ */
88
+ var mapError$1 = function (f, r) {
89
+ return r.ok === true ? r : err$1(f(r.error));
90
+ };
91
+ /**
92
+ * Chain together a sequence of computations that may fail, similar to a
93
+ * `Promise`. If the first computation fails then the error will propagate
94
+ * through. If it succeeds, then `f` will be applied to the value, returning a
95
+ * new `Result`.
96
+ */
97
+ var andThen$1 = function (f, r) {
98
+ return r.ok === true ? f(r.result) : r;
99
+ };
100
+
101
+ /*! *****************************************************************************
102
+ Copyright (c) Microsoft Corporation.
103
+
104
+ Permission to use, copy, modify, and/or distribute this software for any
105
+ purpose with or without fee is hereby granted.
106
+
107
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
108
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
109
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
110
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
111
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
112
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
113
+ PERFORMANCE OF THIS SOFTWARE.
114
+ ***************************************************************************** */
115
+ /* global Reflect, Promise */
116
+
117
+
118
+
119
+ var __assign$1 = function() {
120
+ __assign$1 = Object.assign || function __assign(t) {
121
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
122
+ s = arguments[i];
123
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
124
+ }
125
+ return t;
126
+ };
127
+ return __assign$1.apply(this, arguments);
128
+ };
129
+
130
+ function __rest$1(s, e) {
131
+ var t = {};
132
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
133
+ t[p] = s[p];
134
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
135
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
136
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
137
+ t[p[i]] = s[p[i]];
138
+ }
139
+ return t;
140
+ }
141
+
142
+ function isEqual$1(a, b) {
143
+ if (a === b) {
144
+ return true;
145
+ }
146
+ if (a === null && b === null) {
147
+ return true;
148
+ }
149
+ if (typeof (a) !== typeof (b)) {
150
+ return false;
151
+ }
152
+ if (typeof (a) === 'object') {
153
+ // Array
154
+ if (Array.isArray(a)) {
155
+ if (!Array.isArray(b)) {
156
+ return false;
157
+ }
158
+ if (a.length !== b.length) {
159
+ return false;
160
+ }
161
+ for (var i = 0; i < a.length; i++) {
162
+ if (!isEqual$1(a[i], b[i])) {
163
+ return false;
164
+ }
165
+ }
166
+ return true;
167
+ }
168
+ // Hash table
169
+ var keys = Object.keys(a);
170
+ if (keys.length !== Object.keys(b).length) {
171
+ return false;
172
+ }
173
+ for (var i = 0; i < keys.length; i++) {
174
+ if (!b.hasOwnProperty(keys[i])) {
175
+ return false;
176
+ }
177
+ if (!isEqual$1(a[keys[i]], b[keys[i]])) {
178
+ return false;
179
+ }
180
+ }
181
+ return true;
182
+ }
183
+ }
184
+ /*
185
+ * Helpers
186
+ */
187
+ var isJsonArray$1 = function (json) { return Array.isArray(json); };
188
+ var isJsonObject$1 = function (json) {
189
+ return typeof json === 'object' && json !== null && !isJsonArray$1(json);
190
+ };
191
+ var typeString$1 = function (json) {
192
+ switch (typeof json) {
193
+ case 'string':
194
+ return 'a string';
195
+ case 'number':
196
+ return 'a number';
197
+ case 'boolean':
198
+ return 'a boolean';
199
+ case 'undefined':
200
+ return 'undefined';
201
+ case 'object':
202
+ if (json instanceof Array) {
203
+ return 'an array';
204
+ }
205
+ else if (json === null) {
206
+ return 'null';
207
+ }
208
+ else {
209
+ return 'an object';
210
+ }
211
+ default:
212
+ return JSON.stringify(json);
213
+ }
214
+ };
215
+ var expectedGot$1 = function (expected, got) {
216
+ return "expected " + expected + ", got " + typeString$1(got);
217
+ };
218
+ var printPath$1 = function (paths) {
219
+ return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join('');
220
+ };
221
+ var prependAt$1 = function (newAt, _a) {
222
+ var at = _a.at, rest = __rest$1(_a, ["at"]);
223
+ return (__assign$1({ at: newAt + (at || '') }, rest));
224
+ };
225
+ /**
226
+ * Decoders transform json objects with unknown structure into known and
227
+ * verified forms. You can create objects of type `Decoder<A>` with either the
228
+ * primitive decoder functions, such as `boolean()` and `string()`, or by
229
+ * applying higher-order decoders to the primitives, such as `array(boolean())`
230
+ * or `dict(string())`.
231
+ *
232
+ * Each of the decoder functions are available both as a static method on
233
+ * `Decoder` and as a function alias -- for example the string decoder is
234
+ * defined at `Decoder.string()`, but is also aliased to `string()`. Using the
235
+ * function aliases exported with the library is recommended.
236
+ *
237
+ * `Decoder` exposes a number of 'run' methods, which all decode json in the
238
+ * same way, but communicate success and failure in different ways. The `map`
239
+ * and `andThen` methods modify decoders without having to call a 'run' method.
240
+ *
241
+ * Alternatively, the main decoder `run()` method returns an object of type
242
+ * `Result<A, DecoderError>`. This library provides a number of helper
243
+ * functions for dealing with the `Result` type, so you can do all the same
244
+ * things with a `Result` as with the decoder methods.
245
+ */
246
+ var Decoder$1 = /** @class */ (function () {
247
+ /**
248
+ * The Decoder class constructor is kept private to separate the internal
249
+ * `decode` function from the external `run` function. The distinction
250
+ * between the two functions is that `decode` returns a
251
+ * `Partial<DecoderError>` on failure, which contains an unfinished error
252
+ * report. When `run` is called on a decoder, the relevant series of `decode`
253
+ * calls is made, and then on failure the resulting `Partial<DecoderError>`
254
+ * is turned into a `DecoderError` by filling in the missing information.
255
+ *
256
+ * While hiding the constructor may seem restrictive, leveraging the
257
+ * provided decoder combinators and helper functions such as
258
+ * `andThen` and `map` should be enough to build specialized decoders as
259
+ * needed.
260
+ */
261
+ function Decoder(decode) {
262
+ var _this = this;
263
+ this.decode = decode;
264
+ /**
265
+ * Run the decoder and return a `Result` with either the decoded value or a
266
+ * `DecoderError` containing the json input, the location of the error, and
267
+ * the error message.
268
+ *
269
+ * Examples:
270
+ * ```
271
+ * number().run(12)
272
+ * // => {ok: true, result: 12}
273
+ *
274
+ * string().run(9001)
275
+ * // =>
276
+ * // {
277
+ * // ok: false,
278
+ * // error: {
279
+ * // kind: 'DecoderError',
280
+ * // input: 9001,
281
+ * // at: 'input',
282
+ * // message: 'expected a string, got 9001'
283
+ * // }
284
+ * // }
285
+ * ```
286
+ */
287
+ this.run = function (json) {
288
+ return mapError$1(function (error) { return ({
289
+ kind: 'DecoderError',
290
+ input: json,
291
+ at: 'input' + (error.at || ''),
292
+ message: error.message || ''
293
+ }); }, _this.decode(json));
294
+ };
295
+ /**
296
+ * Run the decoder as a `Promise`.
297
+ */
298
+ this.runPromise = function (json) { return asPromise$1(_this.run(json)); };
299
+ /**
300
+ * Run the decoder and return the value on success, or throw an exception
301
+ * with a formatted error string.
302
+ */
303
+ this.runWithException = function (json) { return withException$1(_this.run(json)); };
304
+ /**
305
+ * Construct a new decoder that applies a transformation to the decoded
306
+ * result. If the decoder succeeds then `f` will be applied to the value. If
307
+ * it fails the error will propagated through.
308
+ *
309
+ * Example:
310
+ * ```
311
+ * number().map(x => x * 5).run(10)
312
+ * // => {ok: true, result: 50}
313
+ * ```
314
+ */
315
+ this.map = function (f) {
316
+ return new Decoder(function (json) { return map$1(f, _this.decode(json)); });
317
+ };
318
+ /**
319
+ * Chain together a sequence of decoders. The first decoder will run, and
320
+ * then the function will determine what decoder to run second. If the result
321
+ * of the first decoder succeeds then `f` will be applied to the decoded
322
+ * value. If it fails the error will propagate through.
323
+ *
324
+ * This is a very powerful method -- it can act as both the `map` and `where`
325
+ * methods, can improve error messages for edge cases, and can be used to
326
+ * make a decoder for custom types.
327
+ *
328
+ * Example of adding an error message:
329
+ * ```
330
+ * const versionDecoder = valueAt(['version'], number());
331
+ * const infoDecoder3 = object({a: boolean()});
332
+ *
333
+ * const decoder = versionDecoder.andThen(version => {
334
+ * switch (version) {
335
+ * case 3:
336
+ * return infoDecoder3;
337
+ * default:
338
+ * return fail(`Unable to decode info, version ${version} is not supported.`);
339
+ * }
340
+ * });
341
+ *
342
+ * decoder.run({version: 3, a: true})
343
+ * // => {ok: true, result: {a: true}}
344
+ *
345
+ * decoder.run({version: 5, x: 'abc'})
346
+ * // =>
347
+ * // {
348
+ * // ok: false,
349
+ * // error: {... message: 'Unable to decode info, version 5 is not supported.'}
350
+ * // }
351
+ * ```
352
+ *
353
+ * Example of decoding a custom type:
354
+ * ```
355
+ * // nominal type for arrays with a length of at least one
356
+ * type NonEmptyArray<T> = T[] & { __nonEmptyArrayBrand__: void };
357
+ *
358
+ * const nonEmptyArrayDecoder = <T>(values: Decoder<T>): Decoder<NonEmptyArray<T>> =>
359
+ * array(values).andThen(arr =>
360
+ * arr.length > 0
361
+ * ? succeed(createNonEmptyArray(arr))
362
+ * : fail(`expected a non-empty array, got an empty array`)
363
+ * );
364
+ * ```
365
+ */
366
+ this.andThen = function (f) {
367
+ return new Decoder(function (json) {
368
+ return andThen$1(function (value) { return f(value).decode(json); }, _this.decode(json));
369
+ });
370
+ };
371
+ /**
372
+ * Add constraints to a decoder _without_ changing the resulting type. The
373
+ * `test` argument is a predicate function which returns true for valid
374
+ * inputs. When `test` fails on an input, the decoder fails with the given
375
+ * `errorMessage`.
376
+ *
377
+ * ```
378
+ * const chars = (length: number): Decoder<string> =>
379
+ * string().where(
380
+ * (s: string) => s.length === length,
381
+ * `expected a string of length ${length}`
382
+ * );
383
+ *
384
+ * chars(5).run('12345')
385
+ * // => {ok: true, result: '12345'}
386
+ *
387
+ * chars(2).run('HELLO')
388
+ * // => {ok: false, error: {... message: 'expected a string of length 2'}}
389
+ *
390
+ * chars(12).run(true)
391
+ * // => {ok: false, error: {... message: 'expected a string, got a boolean'}}
392
+ * ```
393
+ */
394
+ this.where = function (test, errorMessage) {
395
+ return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); });
396
+ };
397
+ }
398
+ /**
399
+ * Decoder primitive that validates strings, and fails on all other input.
400
+ */
401
+ Decoder.string = function () {
402
+ return new Decoder(function (json) {
403
+ return typeof json === 'string'
404
+ ? ok$1(json)
405
+ : err$1({ message: expectedGot$1('a string', json) });
406
+ });
407
+ };
408
+ /**
409
+ * Decoder primitive that validates numbers, and fails on all other input.
410
+ */
411
+ Decoder.number = function () {
412
+ return new Decoder(function (json) {
413
+ return typeof json === 'number'
414
+ ? ok$1(json)
415
+ : err$1({ message: expectedGot$1('a number', json) });
416
+ });
417
+ };
418
+ /**
419
+ * Decoder primitive that validates booleans, and fails on all other input.
420
+ */
421
+ Decoder.boolean = function () {
422
+ return new Decoder(function (json) {
423
+ return typeof json === 'boolean'
424
+ ? ok$1(json)
425
+ : err$1({ message: expectedGot$1('a boolean', json) });
426
+ });
427
+ };
428
+ Decoder.constant = function (value) {
429
+ return new Decoder(function (json) {
430
+ return isEqual$1(json, value)
431
+ ? ok$1(value)
432
+ : err$1({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) });
433
+ });
434
+ };
435
+ Decoder.object = function (decoders) {
436
+ return new Decoder(function (json) {
437
+ if (isJsonObject$1(json) && decoders) {
438
+ var obj = {};
439
+ for (var key in decoders) {
440
+ if (decoders.hasOwnProperty(key)) {
441
+ var r = decoders[key].decode(json[key]);
442
+ if (r.ok === true) {
443
+ // tslint:disable-next-line:strict-type-predicates
444
+ if (r.result !== undefined) {
445
+ obj[key] = r.result;
446
+ }
447
+ }
448
+ else if (json[key] === undefined) {
449
+ return err$1({ message: "the key '" + key + "' is required but was not present" });
450
+ }
451
+ else {
452
+ return err$1(prependAt$1("." + key, r.error));
453
+ }
454
+ }
455
+ }
456
+ return ok$1(obj);
457
+ }
458
+ else if (isJsonObject$1(json)) {
459
+ return ok$1(json);
460
+ }
461
+ else {
462
+ return err$1({ message: expectedGot$1('an object', json) });
463
+ }
464
+ });
465
+ };
466
+ Decoder.array = function (decoder) {
467
+ return new Decoder(function (json) {
468
+ if (isJsonArray$1(json) && decoder) {
469
+ var decodeValue_1 = function (v, i) {
470
+ return mapError$1(function (err$$1) { return prependAt$1("[" + i + "]", err$$1); }, decoder.decode(v));
471
+ };
472
+ return json.reduce(function (acc, v, i) {
473
+ return map2$1(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i));
474
+ }, ok$1([]));
475
+ }
476
+ else if (isJsonArray$1(json)) {
477
+ return ok$1(json);
478
+ }
479
+ else {
480
+ return err$1({ message: expectedGot$1('an array', json) });
481
+ }
482
+ });
483
+ };
484
+ Decoder.tuple = function (decoders) {
485
+ return new Decoder(function (json) {
486
+ if (isJsonArray$1(json)) {
487
+ if (json.length !== decoders.length) {
488
+ return err$1({
489
+ message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length
490
+ });
491
+ }
492
+ var result = [];
493
+ for (var i = 0; i < decoders.length; i++) {
494
+ var nth = decoders[i].decode(json[i]);
495
+ if (nth.ok) {
496
+ result[i] = nth.result;
497
+ }
498
+ else {
499
+ return err$1(prependAt$1("[" + i + "]", nth.error));
500
+ }
501
+ }
502
+ return ok$1(result);
503
+ }
504
+ else {
505
+ return err$1({ message: expectedGot$1("a tuple of length " + decoders.length, json) });
506
+ }
507
+ });
508
+ };
509
+ Decoder.union = function (ad, bd) {
510
+ var decoders = [];
511
+ for (var _i = 2; _i < arguments.length; _i++) {
512
+ decoders[_i - 2] = arguments[_i];
513
+ }
514
+ return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders));
515
+ };
516
+ Decoder.intersection = function (ad, bd) {
517
+ var ds = [];
518
+ for (var _i = 2; _i < arguments.length; _i++) {
519
+ ds[_i - 2] = arguments[_i];
520
+ }
521
+ return new Decoder(function (json) {
522
+ return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$1(Object.assign, acc, decoder.decode(json)); }, ok$1({}));
523
+ });
524
+ };
525
+ /**
526
+ * Escape hatch to bypass validation. Always succeeds and types the result as
527
+ * `any`. Useful for defining decoders incrementally, particularly for
528
+ * complex objects.
529
+ *
530
+ * Example:
531
+ * ```
532
+ * interface User {
533
+ * name: string;
534
+ * complexUserData: ComplexType;
535
+ * }
536
+ *
537
+ * const userDecoder: Decoder<User> = object({
538
+ * name: string(),
539
+ * complexUserData: anyJson()
540
+ * });
541
+ * ```
542
+ */
543
+ Decoder.anyJson = function () { return new Decoder(function (json) { return ok$1(json); }); };
544
+ /**
545
+ * Decoder identity function which always succeeds and types the result as
546
+ * `unknown`.
547
+ */
548
+ Decoder.unknownJson = function () {
549
+ return new Decoder(function (json) { return ok$1(json); });
550
+ };
551
+ /**
552
+ * Decoder for json objects where the keys are unknown strings, but the values
553
+ * should all be of the same type.
554
+ *
555
+ * Example:
556
+ * ```
557
+ * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37});
558
+ * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}}
559
+ * ```
560
+ */
561
+ Decoder.dict = function (decoder) {
562
+ return new Decoder(function (json) {
563
+ if (isJsonObject$1(json)) {
564
+ var obj = {};
565
+ for (var key in json) {
566
+ if (json.hasOwnProperty(key)) {
567
+ var r = decoder.decode(json[key]);
568
+ if (r.ok === true) {
569
+ obj[key] = r.result;
570
+ }
571
+ else {
572
+ return err$1(prependAt$1("." + key, r.error));
573
+ }
574
+ }
575
+ }
576
+ return ok$1(obj);
577
+ }
578
+ else {
579
+ return err$1({ message: expectedGot$1('an object', json) });
580
+ }
581
+ });
582
+ };
583
+ /**
584
+ * Decoder for values that may be `undefined`. This is primarily helpful for
585
+ * decoding interfaces with optional fields.
586
+ *
587
+ * Example:
588
+ * ```
589
+ * interface User {
590
+ * id: number;
591
+ * isOwner?: boolean;
592
+ * }
593
+ *
594
+ * const decoder: Decoder<User> = object({
595
+ * id: number(),
596
+ * isOwner: optional(boolean())
597
+ * });
598
+ * ```
599
+ */
600
+ Decoder.optional = function (decoder) {
601
+ return new Decoder(function (json) { return (json === undefined || json === null ? ok$1(undefined) : decoder.decode(json)); });
602
+ };
603
+ /**
604
+ * Decoder that attempts to run each decoder in `decoders` and either succeeds
605
+ * with the first successful decoder, or fails after all decoders have failed.
606
+ *
607
+ * Note that `oneOf` expects the decoders to all have the same return type,
608
+ * while `union` creates a decoder for the union type of all the input
609
+ * decoders.
610
+ *
611
+ * Examples:
612
+ * ```
613
+ * oneOf(string(), number().map(String))
614
+ * oneOf(constant('start'), constant('stop'), succeed('unknown'))
615
+ * ```
616
+ */
617
+ Decoder.oneOf = function () {
618
+ var decoders = [];
619
+ for (var _i = 0; _i < arguments.length; _i++) {
620
+ decoders[_i] = arguments[_i];
621
+ }
622
+ return new Decoder(function (json) {
623
+ var errors = [];
624
+ for (var i = 0; i < decoders.length; i++) {
625
+ var r = decoders[i].decode(json);
626
+ if (r.ok === true) {
627
+ return r;
628
+ }
629
+ else {
630
+ errors[i] = r.error;
631
+ }
632
+ }
633
+ var errorsList = errors
634
+ .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; })
635
+ .join('", "');
636
+ return err$1({
637
+ message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]"
638
+ });
639
+ });
640
+ };
641
+ /**
642
+ * Decoder that always succeeds with either the decoded value, or a fallback
643
+ * default value.
644
+ */
645
+ Decoder.withDefault = function (defaultValue, decoder) {
646
+ return new Decoder(function (json) {
647
+ return ok$1(withDefault$1(defaultValue, decoder.decode(json)));
648
+ });
649
+ };
650
+ /**
651
+ * Decoder that pulls a specific field out of a json structure, instead of
652
+ * decoding and returning the full structure. The `paths` array describes the
653
+ * object keys and array indices to traverse, so that values can be pulled out
654
+ * of a nested structure.
655
+ *
656
+ * Example:
657
+ * ```
658
+ * const decoder = valueAt(['a', 'b', 0], string());
659
+ *
660
+ * decoder.run({a: {b: ['surprise!']}})
661
+ * // => {ok: true, result: 'surprise!'}
662
+ *
663
+ * decoder.run({a: {x: 'cats'}})
664
+ * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}}
665
+ * ```
666
+ *
667
+ * Note that the `decoder` is ran on the value found at the last key in the
668
+ * path, even if the last key is not found. This allows the `optional`
669
+ * decoder to succeed when appropriate.
670
+ * ```
671
+ * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string()));
672
+ *
673
+ * optionalDecoder.run({a: {b: {c: 'surprise!'}}})
674
+ * // => {ok: true, result: 'surprise!'}
675
+ *
676
+ * optionalDecoder.run({a: {b: 'cats'}})
677
+ * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'}
678
+ *
679
+ * optionalDecoder.run({a: {b: {z: 1}}})
680
+ * // => {ok: true, result: undefined}
681
+ * ```
682
+ */
683
+ Decoder.valueAt = function (paths, decoder) {
684
+ return new Decoder(function (json) {
685
+ var jsonAtPath = json;
686
+ for (var i = 0; i < paths.length; i++) {
687
+ if (jsonAtPath === undefined) {
688
+ return err$1({
689
+ at: printPath$1(paths.slice(0, i + 1)),
690
+ message: 'path does not exist'
691
+ });
692
+ }
693
+ else if (typeof paths[i] === 'string' && !isJsonObject$1(jsonAtPath)) {
694
+ return err$1({
695
+ at: printPath$1(paths.slice(0, i + 1)),
696
+ message: expectedGot$1('an object', jsonAtPath)
697
+ });
698
+ }
699
+ else if (typeof paths[i] === 'number' && !isJsonArray$1(jsonAtPath)) {
700
+ return err$1({
701
+ at: printPath$1(paths.slice(0, i + 1)),
702
+ message: expectedGot$1('an array', jsonAtPath)
703
+ });
704
+ }
705
+ else {
706
+ jsonAtPath = jsonAtPath[paths[i]];
707
+ }
708
+ }
709
+ return mapError$1(function (error) {
710
+ return jsonAtPath === undefined
711
+ ? { at: printPath$1(paths), message: 'path does not exist' }
712
+ : prependAt$1(printPath$1(paths), error);
713
+ }, decoder.decode(jsonAtPath));
714
+ });
715
+ };
716
+ /**
717
+ * Decoder that ignores the input json and always succeeds with `fixedValue`.
718
+ */
719
+ Decoder.succeed = function (fixedValue) {
720
+ return new Decoder(function (json) { return ok$1(fixedValue); });
721
+ };
722
+ /**
723
+ * Decoder that ignores the input json and always fails with `errorMessage`.
724
+ */
725
+ Decoder.fail = function (errorMessage) {
726
+ return new Decoder(function (json) { return err$1({ message: errorMessage }); });
727
+ };
728
+ /**
729
+ * Decoder that allows for validating recursive data structures. Unlike with
730
+ * functions, decoders assigned to variables can't reference themselves
731
+ * before they are fully defined. We can avoid prematurely referencing the
732
+ * decoder by wrapping it in a function that won't be called until use, at
733
+ * which point the decoder has been defined.
734
+ *
735
+ * Example:
736
+ * ```
737
+ * interface Comment {
738
+ * msg: string;
739
+ * replies: Comment[];
740
+ * }
741
+ *
742
+ * const decoder: Decoder<Comment> = object({
743
+ * msg: string(),
744
+ * replies: lazy(() => array(decoder))
745
+ * });
746
+ * ```
747
+ */
748
+ Decoder.lazy = function (mkDecoder) {
749
+ return new Decoder(function (json) { return mkDecoder().decode(json); });
750
+ };
751
+ return Decoder;
752
+ }());
753
+
754
+ /* tslint:disable:variable-name */
755
+ /** See `Decoder.string` */
756
+ var string$1 = Decoder$1.string;
757
+ /** See `Decoder.number` */
758
+ Decoder$1.number;
759
+ /** See `Decoder.boolean` */
760
+ var boolean$1 = Decoder$1.boolean;
761
+ /** See `Decoder.anyJson` */
762
+ var anyJson$1 = Decoder$1.anyJson;
763
+ /** See `Decoder.unknownJson` */
764
+ Decoder$1.unknownJson;
765
+ /** See `Decoder.constant` */
766
+ var constant$1 = Decoder$1.constant;
767
+ /** See `Decoder.object` */
768
+ var object$1 = Decoder$1.object;
769
+ /** See `Decoder.array` */
770
+ var array$1 = Decoder$1.array;
771
+ /** See `Decoder.tuple` */
772
+ Decoder$1.tuple;
773
+ /** See `Decoder.dict` */
774
+ Decoder$1.dict;
775
+ /** See `Decoder.optional` */
776
+ var optional$1 = Decoder$1.optional;
777
+ /** See `Decoder.oneOf` */
778
+ var oneOf$1 = Decoder$1.oneOf;
779
+ /** See `Decoder.union` */
780
+ Decoder$1.union;
781
+ /** See `Decoder.intersection` */
782
+ Decoder$1.intersection;
783
+ /** See `Decoder.withDefault` */
784
+ Decoder$1.withDefault;
785
+ /** See `Decoder.valueAt` */
786
+ Decoder$1.valueAt;
787
+ /** See `Decoder.succeed` */
788
+ Decoder$1.succeed;
789
+ /** See `Decoder.fail` */
790
+ Decoder$1.fail;
791
+ /** See `Decoder.lazy` */
792
+ Decoder$1.lazy;
793
+
794
+ const connectBrowserAppProps = ["name", "title", "version", "customProperties", "icon", "caption", "type"];
795
+ const fdc3v2AppProps = ["appId", "name", "type", "details", "version", "title", "tooltip", "lang", "description", "categories", "icons", "screenshots", "contactEmail", "moreInfo", "publisher", "customConfig", "hostManifests", "interop", "localizedVersions"];
796
+
797
+ /**
798
+ * Wraps values in an `Ok` type.
799
+ *
800
+ * Example: `ok(5) // => {ok: true, result: 5}`
801
+ */
802
+ var ok = function (result) { return ({ ok: true, result: result }); };
803
+ /**
804
+ * Wraps errors in an `Err` type.
805
+ *
806
+ * Example: `err('on fire') // => {ok: false, error: 'on fire'}`
807
+ */
808
+ var err = function (error) { return ({ ok: false, error: error }); };
809
+ /**
810
+ * Create a `Promise` that either resolves with the result of `Ok` or rejects
811
+ * with the error of `Err`.
812
+ */
813
+ var asPromise = function (r) {
814
+ return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error);
815
+ };
816
+ /**
817
+ * Unwraps a `Result` and returns either the result of an `Ok`, or
818
+ * `defaultValue`.
819
+ *
820
+ * Example:
821
+ * ```
822
+ * Result.withDefault(5, number().run(json))
823
+ * ```
824
+ *
825
+ * It would be nice if `Decoder` had an instance method that mirrored this
826
+ * function. Such a method would look something like this:
827
+ * ```
828
+ * class Decoder<A> {
829
+ * runWithDefault = (defaultValue: A, json: any): A =>
830
+ * Result.withDefault(defaultValue, this.run(json));
831
+ * }
832
+ *
833
+ * number().runWithDefault(5, json)
834
+ * ```
835
+ * Unfortunately, the type of `defaultValue: A` on the method causes issues
836
+ * with type inference on the `object` decoder in some situations. While these
837
+ * inference issues can be solved by providing the optional type argument for
838
+ * `object`s, the extra trouble and confusion doesn't seem worth it.
839
+ */
840
+ var withDefault = function (defaultValue, r) {
841
+ return r.ok === true ? r.result : defaultValue;
842
+ };
843
+ /**
844
+ * Return the successful result, or throw an error.
845
+ */
846
+ var withException = function (r) {
847
+ if (r.ok === true) {
848
+ return r.result;
849
+ }
850
+ else {
851
+ throw r.error;
852
+ }
853
+ };
854
+ /**
855
+ * Apply `f` to the result of an `Ok`, or pass the error through.
856
+ */
857
+ var map = function (f, r) {
858
+ return r.ok === true ? ok(f(r.result)) : r;
859
+ };
860
+ /**
861
+ * Apply `f` to the result of two `Ok`s, or pass an error through. If both
862
+ * `Result`s are errors then the first one is returned.
863
+ */
864
+ var map2 = function (f, ar, br) {
865
+ return ar.ok === false ? ar :
866
+ br.ok === false ? br :
867
+ ok(f(ar.result, br.result));
868
+ };
869
+ /**
870
+ * Apply `f` to the error of an `Err`, or pass the success through.
871
+ */
872
+ var mapError = function (f, r) {
873
+ return r.ok === true ? r : err(f(r.error));
874
+ };
875
+ /**
876
+ * Chain together a sequence of computations that may fail, similar to a
877
+ * `Promise`. If the first computation fails then the error will propagate
878
+ * through. If it succeeds, then `f` will be applied to the value, returning a
879
+ * new `Result`.
880
+ */
881
+ var andThen = function (f, r) {
882
+ return r.ok === true ? f(r.result) : r;
883
+ };
884
+
885
+ /*! *****************************************************************************
886
+ Copyright (c) Microsoft Corporation.
887
+
888
+ Permission to use, copy, modify, and/or distribute this software for any
889
+ purpose with or without fee is hereby granted.
890
+
891
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
892
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
893
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
894
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
895
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
896
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
897
+ PERFORMANCE OF THIS SOFTWARE.
898
+ ***************************************************************************** */
899
+ /* global Reflect, Promise */
900
+
901
+
902
+
903
+ var __assign = function() {
904
+ __assign = Object.assign || function __assign(t) {
905
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
906
+ s = arguments[i];
907
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
908
+ }
909
+ return t;
910
+ };
911
+ return __assign.apply(this, arguments);
912
+ };
913
+
914
+ function __rest(s, e) {
915
+ var t = {};
916
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
917
+ t[p] = s[p];
918
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
919
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
920
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
921
+ t[p[i]] = s[p[i]];
922
+ }
923
+ return t;
924
+ }
925
+
926
+ function isEqual(a, b) {
927
+ if (a === b) {
928
+ return true;
929
+ }
930
+ if (a === null && b === null) {
931
+ return true;
932
+ }
933
+ if (typeof (a) !== typeof (b)) {
934
+ return false;
935
+ }
936
+ if (typeof (a) === 'object') {
937
+ // Array
938
+ if (Array.isArray(a)) {
939
+ if (!Array.isArray(b)) {
940
+ return false;
941
+ }
942
+ if (a.length !== b.length) {
943
+ return false;
944
+ }
945
+ for (var i = 0; i < a.length; i++) {
946
+ if (!isEqual(a[i], b[i])) {
947
+ return false;
948
+ }
949
+ }
950
+ return true;
951
+ }
952
+ // Hash table
953
+ var keys = Object.keys(a);
954
+ if (keys.length !== Object.keys(b).length) {
955
+ return false;
956
+ }
957
+ for (var i = 0; i < keys.length; i++) {
958
+ if (!b.hasOwnProperty(keys[i])) {
959
+ return false;
960
+ }
961
+ if (!isEqual(a[keys[i]], b[keys[i]])) {
962
+ return false;
963
+ }
964
+ }
965
+ return true;
966
+ }
967
+ }
968
+ /*
969
+ * Helpers
970
+ */
971
+ var isJsonArray = function (json) { return Array.isArray(json); };
972
+ var isJsonObject = function (json) {
973
+ return typeof json === 'object' && json !== null && !isJsonArray(json);
974
+ };
975
+ var typeString = function (json) {
976
+ switch (typeof json) {
977
+ case 'string':
978
+ return 'a string';
979
+ case 'number':
980
+ return 'a number';
981
+ case 'boolean':
982
+ return 'a boolean';
983
+ case 'undefined':
984
+ return 'undefined';
985
+ case 'object':
986
+ if (json instanceof Array) {
987
+ return 'an array';
988
+ }
989
+ else if (json === null) {
990
+ return 'null';
991
+ }
992
+ else {
993
+ return 'an object';
994
+ }
995
+ default:
996
+ return JSON.stringify(json);
997
+ }
998
+ };
999
+ var expectedGot = function (expected, got) {
1000
+ return "expected " + expected + ", got " + typeString(got);
1001
+ };
1002
+ var printPath = function (paths) {
1003
+ return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join('');
1004
+ };
1005
+ var prependAt = function (newAt, _a) {
1006
+ var at = _a.at, rest = __rest(_a, ["at"]);
1007
+ return (__assign({ at: newAt + (at || '') }, rest));
1008
+ };
1009
+ /**
1010
+ * Decoders transform json objects with unknown structure into known and
1011
+ * verified forms. You can create objects of type `Decoder<A>` with either the
1012
+ * primitive decoder functions, such as `boolean()` and `string()`, or by
1013
+ * applying higher-order decoders to the primitives, such as `array(boolean())`
1014
+ * or `dict(string())`.
1015
+ *
1016
+ * Each of the decoder functions are available both as a static method on
1017
+ * `Decoder` and as a function alias -- for example the string decoder is
1018
+ * defined at `Decoder.string()`, but is also aliased to `string()`. Using the
1019
+ * function aliases exported with the library is recommended.
1020
+ *
1021
+ * `Decoder` exposes a number of 'run' methods, which all decode json in the
1022
+ * same way, but communicate success and failure in different ways. The `map`
1023
+ * and `andThen` methods modify decoders without having to call a 'run' method.
1024
+ *
1025
+ * Alternatively, the main decoder `run()` method returns an object of type
1026
+ * `Result<A, DecoderError>`. This library provides a number of helper
1027
+ * functions for dealing with the `Result` type, so you can do all the same
1028
+ * things with a `Result` as with the decoder methods.
1029
+ */
1030
+ var Decoder = /** @class */ (function () {
1031
+ /**
1032
+ * The Decoder class constructor is kept private to separate the internal
1033
+ * `decode` function from the external `run` function. The distinction
1034
+ * between the two functions is that `decode` returns a
1035
+ * `Partial<DecoderError>` on failure, which contains an unfinished error
1036
+ * report. When `run` is called on a decoder, the relevant series of `decode`
1037
+ * calls is made, and then on failure the resulting `Partial<DecoderError>`
1038
+ * is turned into a `DecoderError` by filling in the missing information.
1039
+ *
1040
+ * While hiding the constructor may seem restrictive, leveraging the
1041
+ * provided decoder combinators and helper functions such as
1042
+ * `andThen` and `map` should be enough to build specialized decoders as
1043
+ * needed.
1044
+ */
1045
+ function Decoder(decode) {
1046
+ var _this = this;
1047
+ this.decode = decode;
1048
+ /**
1049
+ * Run the decoder and return a `Result` with either the decoded value or a
1050
+ * `DecoderError` containing the json input, the location of the error, and
1051
+ * the error message.
1052
+ *
1053
+ * Examples:
1054
+ * ```
1055
+ * number().run(12)
1056
+ * // => {ok: true, result: 12}
1057
+ *
1058
+ * string().run(9001)
1059
+ * // =>
1060
+ * // {
1061
+ * // ok: false,
1062
+ * // error: {
1063
+ * // kind: 'DecoderError',
1064
+ * // input: 9001,
1065
+ * // at: 'input',
1066
+ * // message: 'expected a string, got 9001'
1067
+ * // }
1068
+ * // }
1069
+ * ```
1070
+ */
1071
+ this.run = function (json) {
1072
+ return mapError(function (error) { return ({
1073
+ kind: 'DecoderError',
1074
+ input: json,
1075
+ at: 'input' + (error.at || ''),
1076
+ message: error.message || ''
1077
+ }); }, _this.decode(json));
1078
+ };
1079
+ /**
1080
+ * Run the decoder as a `Promise`.
1081
+ */
1082
+ this.runPromise = function (json) { return asPromise(_this.run(json)); };
1083
+ /**
1084
+ * Run the decoder and return the value on success, or throw an exception
1085
+ * with a formatted error string.
1086
+ */
1087
+ this.runWithException = function (json) { return withException(_this.run(json)); };
1088
+ /**
1089
+ * Construct a new decoder that applies a transformation to the decoded
1090
+ * result. If the decoder succeeds then `f` will be applied to the value. If
1091
+ * it fails the error will propagated through.
1092
+ *
1093
+ * Example:
1094
+ * ```
1095
+ * number().map(x => x * 5).run(10)
1096
+ * // => {ok: true, result: 50}
1097
+ * ```
1098
+ */
1099
+ this.map = function (f) {
1100
+ return new Decoder(function (json) { return map(f, _this.decode(json)); });
1101
+ };
1102
+ /**
1103
+ * Chain together a sequence of decoders. The first decoder will run, and
1104
+ * then the function will determine what decoder to run second. If the result
1105
+ * of the first decoder succeeds then `f` will be applied to the decoded
1106
+ * value. If it fails the error will propagate through.
1107
+ *
1108
+ * This is a very powerful method -- it can act as both the `map` and `where`
1109
+ * methods, can improve error messages for edge cases, and can be used to
1110
+ * make a decoder for custom types.
1111
+ *
1112
+ * Example of adding an error message:
1113
+ * ```
1114
+ * const versionDecoder = valueAt(['version'], number());
1115
+ * const infoDecoder3 = object({a: boolean()});
1116
+ *
1117
+ * const decoder = versionDecoder.andThen(version => {
1118
+ * switch (version) {
1119
+ * case 3:
1120
+ * return infoDecoder3;
1121
+ * default:
1122
+ * return fail(`Unable to decode info, version ${version} is not supported.`);
1123
+ * }
1124
+ * });
1125
+ *
1126
+ * decoder.run({version: 3, a: true})
1127
+ * // => {ok: true, result: {a: true}}
1128
+ *
1129
+ * decoder.run({version: 5, x: 'abc'})
1130
+ * // =>
1131
+ * // {
1132
+ * // ok: false,
1133
+ * // error: {... message: 'Unable to decode info, version 5 is not supported.'}
1134
+ * // }
1135
+ * ```
1136
+ *
1137
+ * Example of decoding a custom type:
1138
+ * ```
1139
+ * // nominal type for arrays with a length of at least one
1140
+ * type NonEmptyArray<T> = T[] & { __nonEmptyArrayBrand__: void };
1141
+ *
1142
+ * const nonEmptyArrayDecoder = <T>(values: Decoder<T>): Decoder<NonEmptyArray<T>> =>
1143
+ * array(values).andThen(arr =>
1144
+ * arr.length > 0
1145
+ * ? succeed(createNonEmptyArray(arr))
1146
+ * : fail(`expected a non-empty array, got an empty array`)
1147
+ * );
1148
+ * ```
1149
+ */
1150
+ this.andThen = function (f) {
1151
+ return new Decoder(function (json) {
1152
+ return andThen(function (value) { return f(value).decode(json); }, _this.decode(json));
1153
+ });
1154
+ };
1155
+ /**
1156
+ * Add constraints to a decoder _without_ changing the resulting type. The
1157
+ * `test` argument is a predicate function which returns true for valid
1158
+ * inputs. When `test` fails on an input, the decoder fails with the given
1159
+ * `errorMessage`.
1160
+ *
1161
+ * ```
1162
+ * const chars = (length: number): Decoder<string> =>
1163
+ * string().where(
1164
+ * (s: string) => s.length === length,
1165
+ * `expected a string of length ${length}`
1166
+ * );
1167
+ *
1168
+ * chars(5).run('12345')
1169
+ * // => {ok: true, result: '12345'}
1170
+ *
1171
+ * chars(2).run('HELLO')
1172
+ * // => {ok: false, error: {... message: 'expected a string of length 2'}}
1173
+ *
1174
+ * chars(12).run(true)
1175
+ * // => {ok: false, error: {... message: 'expected a string, got a boolean'}}
1176
+ * ```
1177
+ */
1178
+ this.where = function (test, errorMessage) {
1179
+ return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); });
1180
+ };
1181
+ }
1182
+ /**
1183
+ * Decoder primitive that validates strings, and fails on all other input.
1184
+ */
1185
+ Decoder.string = function () {
1186
+ return new Decoder(function (json) {
1187
+ return typeof json === 'string'
1188
+ ? ok(json)
1189
+ : err({ message: expectedGot('a string', json) });
1190
+ });
1191
+ };
1192
+ /**
1193
+ * Decoder primitive that validates numbers, and fails on all other input.
1194
+ */
1195
+ Decoder.number = function () {
1196
+ return new Decoder(function (json) {
1197
+ return typeof json === 'number'
1198
+ ? ok(json)
1199
+ : err({ message: expectedGot('a number', json) });
1200
+ });
1201
+ };
1202
+ /**
1203
+ * Decoder primitive that validates booleans, and fails on all other input.
1204
+ */
1205
+ Decoder.boolean = function () {
1206
+ return new Decoder(function (json) {
1207
+ return typeof json === 'boolean'
1208
+ ? ok(json)
1209
+ : err({ message: expectedGot('a boolean', json) });
1210
+ });
1211
+ };
1212
+ Decoder.constant = function (value) {
1213
+ return new Decoder(function (json) {
1214
+ return isEqual(json, value)
1215
+ ? ok(value)
1216
+ : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) });
1217
+ });
1218
+ };
1219
+ Decoder.object = function (decoders) {
1220
+ return new Decoder(function (json) {
1221
+ if (isJsonObject(json) && decoders) {
1222
+ var obj = {};
1223
+ for (var key in decoders) {
1224
+ if (decoders.hasOwnProperty(key)) {
1225
+ var r = decoders[key].decode(json[key]);
1226
+ if (r.ok === true) {
1227
+ // tslint:disable-next-line:strict-type-predicates
1228
+ if (r.result !== undefined) {
1229
+ obj[key] = r.result;
1230
+ }
1231
+ }
1232
+ else if (json[key] === undefined) {
1233
+ return err({ message: "the key '" + key + "' is required but was not present" });
1234
+ }
1235
+ else {
1236
+ return err(prependAt("." + key, r.error));
1237
+ }
1238
+ }
1239
+ }
1240
+ return ok(obj);
1241
+ }
1242
+ else if (isJsonObject(json)) {
1243
+ return ok(json);
1244
+ }
1245
+ else {
1246
+ return err({ message: expectedGot('an object', json) });
1247
+ }
1248
+ });
1249
+ };
1250
+ Decoder.array = function (decoder) {
1251
+ return new Decoder(function (json) {
1252
+ if (isJsonArray(json) && decoder) {
1253
+ var decodeValue_1 = function (v, i) {
1254
+ return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v));
1255
+ };
1256
+ return json.reduce(function (acc, v, i) {
1257
+ return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i));
1258
+ }, ok([]));
1259
+ }
1260
+ else if (isJsonArray(json)) {
1261
+ return ok(json);
1262
+ }
1263
+ else {
1264
+ return err({ message: expectedGot('an array', json) });
1265
+ }
1266
+ });
1267
+ };
1268
+ Decoder.tuple = function (decoders) {
1269
+ return new Decoder(function (json) {
1270
+ if (isJsonArray(json)) {
1271
+ if (json.length !== decoders.length) {
1272
+ return err({
1273
+ message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length
1274
+ });
1275
+ }
1276
+ var result = [];
1277
+ for (var i = 0; i < decoders.length; i++) {
1278
+ var nth = decoders[i].decode(json[i]);
1279
+ if (nth.ok) {
1280
+ result[i] = nth.result;
1281
+ }
1282
+ else {
1283
+ return err(prependAt("[" + i + "]", nth.error));
1284
+ }
1285
+ }
1286
+ return ok(result);
1287
+ }
1288
+ else {
1289
+ return err({ message: expectedGot("a tuple of length " + decoders.length, json) });
1290
+ }
1291
+ });
1292
+ };
1293
+ Decoder.union = function (ad, bd) {
1294
+ var decoders = [];
1295
+ for (var _i = 2; _i < arguments.length; _i++) {
1296
+ decoders[_i - 2] = arguments[_i];
1297
+ }
1298
+ return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders));
1299
+ };
1300
+ Decoder.intersection = function (ad, bd) {
1301
+ var ds = [];
1302
+ for (var _i = 2; _i < arguments.length; _i++) {
1303
+ ds[_i - 2] = arguments[_i];
1304
+ }
1305
+ return new Decoder(function (json) {
1306
+ return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({}));
1307
+ });
1308
+ };
1309
+ /**
1310
+ * Escape hatch to bypass validation. Always succeeds and types the result as
1311
+ * `any`. Useful for defining decoders incrementally, particularly for
1312
+ * complex objects.
1313
+ *
1314
+ * Example:
1315
+ * ```
1316
+ * interface User {
1317
+ * name: string;
1318
+ * complexUserData: ComplexType;
1319
+ * }
1320
+ *
1321
+ * const userDecoder: Decoder<User> = object({
1322
+ * name: string(),
1323
+ * complexUserData: anyJson()
1324
+ * });
1325
+ * ```
1326
+ */
1327
+ Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); };
1328
+ /**
1329
+ * Decoder identity function which always succeeds and types the result as
1330
+ * `unknown`.
1331
+ */
1332
+ Decoder.unknownJson = function () {
1333
+ return new Decoder(function (json) { return ok(json); });
1334
+ };
1335
+ /**
1336
+ * Decoder for json objects where the keys are unknown strings, but the values
1337
+ * should all be of the same type.
1338
+ *
1339
+ * Example:
1340
+ * ```
1341
+ * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37});
1342
+ * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}}
1343
+ * ```
1344
+ */
1345
+ Decoder.dict = function (decoder) {
1346
+ return new Decoder(function (json) {
1347
+ if (isJsonObject(json)) {
1348
+ var obj = {};
1349
+ for (var key in json) {
1350
+ if (json.hasOwnProperty(key)) {
1351
+ var r = decoder.decode(json[key]);
1352
+ if (r.ok === true) {
1353
+ obj[key] = r.result;
1354
+ }
1355
+ else {
1356
+ return err(prependAt("." + key, r.error));
1357
+ }
1358
+ }
1359
+ }
1360
+ return ok(obj);
1361
+ }
1362
+ else {
1363
+ return err({ message: expectedGot('an object', json) });
1364
+ }
1365
+ });
1366
+ };
1367
+ /**
1368
+ * Decoder for values that may be `undefined`. This is primarily helpful for
1369
+ * decoding interfaces with optional fields.
1370
+ *
1371
+ * Example:
1372
+ * ```
1373
+ * interface User {
1374
+ * id: number;
1375
+ * isOwner?: boolean;
1376
+ * }
1377
+ *
1378
+ * const decoder: Decoder<User> = object({
1379
+ * id: number(),
1380
+ * isOwner: optional(boolean())
1381
+ * });
1382
+ * ```
1383
+ */
1384
+ Decoder.optional = function (decoder) {
1385
+ return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); });
1386
+ };
1387
+ /**
1388
+ * Decoder that attempts to run each decoder in `decoders` and either succeeds
1389
+ * with the first successful decoder, or fails after all decoders have failed.
1390
+ *
1391
+ * Note that `oneOf` expects the decoders to all have the same return type,
1392
+ * while `union` creates a decoder for the union type of all the input
1393
+ * decoders.
1394
+ *
1395
+ * Examples:
1396
+ * ```
1397
+ * oneOf(string(), number().map(String))
1398
+ * oneOf(constant('start'), constant('stop'), succeed('unknown'))
1399
+ * ```
1400
+ */
1401
+ Decoder.oneOf = function () {
1402
+ var decoders = [];
1403
+ for (var _i = 0; _i < arguments.length; _i++) {
1404
+ decoders[_i] = arguments[_i];
1405
+ }
1406
+ return new Decoder(function (json) {
1407
+ var errors = [];
1408
+ for (var i = 0; i < decoders.length; i++) {
1409
+ var r = decoders[i].decode(json);
1410
+ if (r.ok === true) {
1411
+ return r;
1412
+ }
1413
+ else {
1414
+ errors[i] = r.error;
1415
+ }
1416
+ }
1417
+ var errorsList = errors
1418
+ .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; })
1419
+ .join('", "');
1420
+ return err({
1421
+ message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]"
1422
+ });
1423
+ });
1424
+ };
1425
+ /**
1426
+ * Decoder that always succeeds with either the decoded value, or a fallback
1427
+ * default value.
1428
+ */
1429
+ Decoder.withDefault = function (defaultValue, decoder) {
1430
+ return new Decoder(function (json) {
1431
+ return ok(withDefault(defaultValue, decoder.decode(json)));
1432
+ });
1433
+ };
1434
+ /**
1435
+ * Decoder that pulls a specific field out of a json structure, instead of
1436
+ * decoding and returning the full structure. The `paths` array describes the
1437
+ * object keys and array indices to traverse, so that values can be pulled out
1438
+ * of a nested structure.
1439
+ *
1440
+ * Example:
1441
+ * ```
1442
+ * const decoder = valueAt(['a', 'b', 0], string());
1443
+ *
1444
+ * decoder.run({a: {b: ['surprise!']}})
1445
+ * // => {ok: true, result: 'surprise!'}
1446
+ *
1447
+ * decoder.run({a: {x: 'cats'}})
1448
+ * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}}
1449
+ * ```
1450
+ *
1451
+ * Note that the `decoder` is ran on the value found at the last key in the
1452
+ * path, even if the last key is not found. This allows the `optional`
1453
+ * decoder to succeed when appropriate.
1454
+ * ```
1455
+ * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string()));
1456
+ *
1457
+ * optionalDecoder.run({a: {b: {c: 'surprise!'}}})
1458
+ * // => {ok: true, result: 'surprise!'}
1459
+ *
1460
+ * optionalDecoder.run({a: {b: 'cats'}})
1461
+ * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'}
1462
+ *
1463
+ * optionalDecoder.run({a: {b: {z: 1}}})
1464
+ * // => {ok: true, result: undefined}
1465
+ * ```
1466
+ */
1467
+ Decoder.valueAt = function (paths, decoder) {
1468
+ return new Decoder(function (json) {
1469
+ var jsonAtPath = json;
1470
+ for (var i = 0; i < paths.length; i++) {
1471
+ if (jsonAtPath === undefined) {
1472
+ return err({
1473
+ at: printPath(paths.slice(0, i + 1)),
1474
+ message: 'path does not exist'
1475
+ });
1476
+ }
1477
+ else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) {
1478
+ return err({
1479
+ at: printPath(paths.slice(0, i + 1)),
1480
+ message: expectedGot('an object', jsonAtPath)
1481
+ });
1482
+ }
1483
+ else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) {
1484
+ return err({
1485
+ at: printPath(paths.slice(0, i + 1)),
1486
+ message: expectedGot('an array', jsonAtPath)
1487
+ });
1488
+ }
1489
+ else {
1490
+ jsonAtPath = jsonAtPath[paths[i]];
1491
+ }
1492
+ }
1493
+ return mapError(function (error) {
1494
+ return jsonAtPath === undefined
1495
+ ? { at: printPath(paths), message: 'path does not exist' }
1496
+ : prependAt(printPath(paths), error);
1497
+ }, decoder.decode(jsonAtPath));
1498
+ });
1499
+ };
1500
+ /**
1501
+ * Decoder that ignores the input json and always succeeds with `fixedValue`.
1502
+ */
1503
+ Decoder.succeed = function (fixedValue) {
1504
+ return new Decoder(function (json) { return ok(fixedValue); });
1505
+ };
1506
+ /**
1507
+ * Decoder that ignores the input json and always fails with `errorMessage`.
1508
+ */
1509
+ Decoder.fail = function (errorMessage) {
1510
+ return new Decoder(function (json) { return err({ message: errorMessage }); });
1511
+ };
1512
+ /**
1513
+ * Decoder that allows for validating recursive data structures. Unlike with
1514
+ * functions, decoders assigned to variables can't reference themselves
1515
+ * before they are fully defined. We can avoid prematurely referencing the
1516
+ * decoder by wrapping it in a function that won't be called until use, at
1517
+ * which point the decoder has been defined.
1518
+ *
1519
+ * Example:
1520
+ * ```
1521
+ * interface Comment {
1522
+ * msg: string;
1523
+ * replies: Comment[];
1524
+ * }
1525
+ *
1526
+ * const decoder: Decoder<Comment> = object({
1527
+ * msg: string(),
1528
+ * replies: lazy(() => array(decoder))
1529
+ * });
1530
+ * ```
1531
+ */
1532
+ Decoder.lazy = function (mkDecoder) {
1533
+ return new Decoder(function (json) { return mkDecoder().decode(json); });
1534
+ };
1535
+ return Decoder;
1536
+ }());
1537
+
1538
+ /* tslint:disable:variable-name */
1539
+ /** See `Decoder.string` */
1540
+ var string = Decoder.string;
1541
+ /** See `Decoder.number` */
1542
+ var number = Decoder.number;
1543
+ /** See `Decoder.boolean` */
1544
+ var boolean = Decoder.boolean;
1545
+ /** See `Decoder.anyJson` */
1546
+ var anyJson = Decoder.anyJson;
1547
+ /** See `Decoder.unknownJson` */
1548
+ Decoder.unknownJson;
1549
+ /** See `Decoder.constant` */
1550
+ var constant = Decoder.constant;
1551
+ /** See `Decoder.object` */
1552
+ var object = Decoder.object;
1553
+ /** See `Decoder.array` */
1554
+ var array = Decoder.array;
1555
+ /** See `Decoder.tuple` */
1556
+ Decoder.tuple;
1557
+ /** See `Decoder.dict` */
1558
+ var dict = Decoder.dict;
1559
+ /** See `Decoder.optional` */
1560
+ var optional = Decoder.optional;
1561
+ /** See `Decoder.oneOf` */
1562
+ var oneOf = Decoder.oneOf;
1563
+ /** See `Decoder.union` */
1564
+ Decoder.union;
1565
+ /** See `Decoder.intersection` */
1566
+ Decoder.intersection;
1567
+ /** See `Decoder.withDefault` */
1568
+ Decoder.withDefault;
1569
+ /** See `Decoder.valueAt` */
1570
+ Decoder.valueAt;
1571
+ /** See `Decoder.succeed` */
1572
+ Decoder.succeed;
1573
+ /** See `Decoder.fail` */
1574
+ Decoder.fail;
1575
+ /** See `Decoder.lazy` */
1576
+ Decoder.lazy;
1577
+
1578
+ const nonEmptyStringDecoder$4 = string().where((s) => s.length > 0, "Expected a non-empty string");
1579
+ const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number");
1580
+
1581
+ const intentDefinitionDecoder = object({
1582
+ name: nonEmptyStringDecoder$4,
1583
+ displayName: optional(string()),
1584
+ contexts: optional(array(string())),
1585
+ customConfig: optional(object())
1586
+ });
1587
+ const v2TypeDecoder = oneOf(constant("web"), constant("native"), constant("citrix"), constant("onlineNative"), constant("other"));
1588
+ const v2DetailsDecoder = object({
1589
+ url: nonEmptyStringDecoder$4
1590
+ });
1591
+ const v2IconDecoder = object({
1592
+ src: nonEmptyStringDecoder$4,
1593
+ size: optional(nonEmptyStringDecoder$4),
1594
+ type: optional(nonEmptyStringDecoder$4)
1595
+ });
1596
+ const v2ScreenshotDecoder = object({
1597
+ src: nonEmptyStringDecoder$4,
1598
+ size: optional(nonEmptyStringDecoder$4),
1599
+ type: optional(nonEmptyStringDecoder$4),
1600
+ label: optional(nonEmptyStringDecoder$4)
1601
+ });
1602
+ const v2ListensForIntentDecoder = object({
1603
+ contexts: array(nonEmptyStringDecoder$4),
1604
+ displayName: optional(nonEmptyStringDecoder$4),
1605
+ resultType: optional(nonEmptyStringDecoder$4),
1606
+ customConfig: optional(anyJson())
1607
+ });
1608
+ const v2IntentsDecoder = object({
1609
+ listensFor: optional(dict(v2ListensForIntentDecoder)),
1610
+ raises: optional(dict(array(nonEmptyStringDecoder$4)))
1611
+ });
1612
+ const v2UserChannelDecoder = object({
1613
+ broadcasts: optional(array(nonEmptyStringDecoder$4)),
1614
+ listensFor: optional(array(nonEmptyStringDecoder$4))
1615
+ });
1616
+ const v2AppChannelDecoder = object({
1617
+ name: nonEmptyStringDecoder$4,
1618
+ description: optional(nonEmptyStringDecoder$4),
1619
+ broadcasts: optional(array(nonEmptyStringDecoder$4)),
1620
+ listensFor: optional(array(nonEmptyStringDecoder$4))
1621
+ });
1622
+ const v2InteropDecoder = object({
1623
+ intents: optional(v2IntentsDecoder),
1624
+ userChannels: optional(v2UserChannelDecoder),
1625
+ appChannels: optional(array(v2AppChannelDecoder))
1626
+ });
1627
+ const glue42ApplicationDetailsDecoder = object({
1628
+ url: optional(nonEmptyStringDecoder$4),
1629
+ top: optional(number()),
1630
+ left: optional(number()),
1631
+ width: optional(nonNegativeNumberDecoder),
1632
+ height: optional(nonNegativeNumberDecoder)
1633
+ });
1634
+ const glue42HostManifestsBrowserDecoder = object({
1635
+ name: optional(nonEmptyStringDecoder$4),
1636
+ type: optional(nonEmptyStringDecoder$4.where((s) => s === "window", "Expected a value of window")),
1637
+ title: optional(nonEmptyStringDecoder$4),
1638
+ version: optional(nonEmptyStringDecoder$4),
1639
+ customProperties: optional(anyJson()),
1640
+ icon: optional(string()),
1641
+ caption: optional(string()),
1642
+ details: optional(glue42ApplicationDetailsDecoder),
1643
+ intents: optional(array(intentDefinitionDecoder)),
1644
+ hidden: optional(boolean())
1645
+ });
1646
+ const v1DefinitionDecoder = object({
1647
+ name: nonEmptyStringDecoder$4,
1648
+ appId: nonEmptyStringDecoder$4,
1649
+ title: optional(nonEmptyStringDecoder$4),
1650
+ version: optional(nonEmptyStringDecoder$4),
1651
+ manifest: nonEmptyStringDecoder$4,
1652
+ manifestType: nonEmptyStringDecoder$4,
1653
+ tooltip: optional(nonEmptyStringDecoder$4),
1654
+ description: optional(nonEmptyStringDecoder$4),
1655
+ contactEmail: optional(nonEmptyStringDecoder$4),
1656
+ supportEmail: optional(nonEmptyStringDecoder$4),
1657
+ publisher: optional(nonEmptyStringDecoder$4),
1658
+ images: optional(array(object({ url: optional(nonEmptyStringDecoder$4) }))),
1659
+ icons: optional(array(object({ icon: optional(nonEmptyStringDecoder$4) }))),
1660
+ customConfig: anyJson(),
1661
+ intents: optional(array(intentDefinitionDecoder))
1662
+ });
1663
+ const v2LocalizedDefinitionDecoder = object({
1664
+ appId: optional(nonEmptyStringDecoder$4),
1665
+ name: optional(nonEmptyStringDecoder$4),
1666
+ details: optional(v2DetailsDecoder),
1667
+ version: optional(nonEmptyStringDecoder$4),
1668
+ title: optional(nonEmptyStringDecoder$4),
1669
+ tooltip: optional(nonEmptyStringDecoder$4),
1670
+ lang: optional(nonEmptyStringDecoder$4),
1671
+ description: optional(nonEmptyStringDecoder$4),
1672
+ categories: optional(array(nonEmptyStringDecoder$4)),
1673
+ icons: optional(array(v2IconDecoder)),
1674
+ screenshots: optional(array(v2ScreenshotDecoder)),
1675
+ contactEmail: optional(nonEmptyStringDecoder$4),
1676
+ supportEmail: optional(nonEmptyStringDecoder$4),
1677
+ moreInfo: optional(nonEmptyStringDecoder$4),
1678
+ publisher: optional(nonEmptyStringDecoder$4),
1679
+ customConfig: optional(array(anyJson())),
1680
+ hostManifests: optional(anyJson()),
1681
+ interop: optional(v2InteropDecoder)
1682
+ });
1683
+ const v2DefinitionDecoder = object({
1684
+ appId: nonEmptyStringDecoder$4,
1685
+ name: nonEmptyStringDecoder$4,
1686
+ type: v2TypeDecoder,
1687
+ details: v2DetailsDecoder,
1688
+ version: optional(nonEmptyStringDecoder$4),
1689
+ title: optional(nonEmptyStringDecoder$4),
1690
+ tooltip: optional(nonEmptyStringDecoder$4),
1691
+ lang: optional(nonEmptyStringDecoder$4),
1692
+ description: optional(nonEmptyStringDecoder$4),
1693
+ categories: optional(array(nonEmptyStringDecoder$4)),
1694
+ icons: optional(array(v2IconDecoder)),
1695
+ screenshots: optional(array(v2ScreenshotDecoder)),
1696
+ contactEmail: optional(nonEmptyStringDecoder$4),
1697
+ supportEmail: optional(nonEmptyStringDecoder$4),
1698
+ moreInfo: optional(nonEmptyStringDecoder$4),
1699
+ publisher: optional(nonEmptyStringDecoder$4),
1700
+ customConfig: optional(array(anyJson())),
1701
+ hostManifests: optional(anyJson()),
1702
+ interop: optional(v2InteropDecoder),
1703
+ localizedVersions: optional(dict(v2LocalizedDefinitionDecoder))
1704
+ });
1705
+ const allDefinitionsDecoder = oneOf(v1DefinitionDecoder, v2DefinitionDecoder);
1706
+
1707
+ const parseDecoderErrorToStringMessage = (error) => {
1708
+ return `${error.kind} at ${error.at}: ${JSON.stringify(error.input)}. Reason - ${error.message}`;
1709
+ };
1710
+
1711
+ class FDC3Service {
1712
+ fdc3ToDesktopDefinitionType = {
1713
+ web: "window",
1714
+ native: "exe",
1715
+ citrix: "citrix",
1716
+ onlineNative: "clickonce",
1717
+ other: "window"
1718
+ };
1719
+ toApi() {
1720
+ return {
1721
+ isFdc3Definition: this.isFdc3Definition.bind(this),
1722
+ parseToBrowserBaseAppData: this.parseToBrowserBaseAppData.bind(this),
1723
+ parseToDesktopAppConfig: this.parseToDesktopAppConfig.bind(this)
1724
+ };
1725
+ }
1726
+ isFdc3Definition(definition) {
1727
+ const decodeRes = allDefinitionsDecoder.run(definition);
1728
+ if (!decodeRes.ok) {
1729
+ return { isFdc3: false, reason: parseDecoderErrorToStringMessage(decodeRes.error) };
1730
+ }
1731
+ if (definition.appId && definition.details) {
1732
+ return { isFdc3: true, version: "2.0" };
1733
+ }
1734
+ if (definition.manifest) {
1735
+ return { isFdc3: true, version: "1.2" };
1736
+ }
1737
+ return { isFdc3: false, reason: "The passed definition is not FDC3" };
1738
+ }
1739
+ parseToBrowserBaseAppData(definition) {
1740
+ const { isFdc3, version } = this.isFdc3Definition(definition);
1741
+ if (!isFdc3) {
1742
+ throw new Error("The passed definition is not FDC3");
1743
+ }
1744
+ const decodeRes = allDefinitionsDecoder.run(definition);
1745
+ if (!decodeRes.ok) {
1746
+ throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`);
1747
+ }
1748
+ const userProperties = this.getUserPropertiesFromDefinition(definition, version);
1749
+ const createOptions = { url: this.getUrl(definition, version) };
1750
+ const baseApplicationData = {
1751
+ name: definition.appId,
1752
+ type: "window",
1753
+ createOptions,
1754
+ userProperties: {
1755
+ ...userProperties,
1756
+ intents: version === "1.2"
1757
+ ? userProperties.intents
1758
+ : this.getIntentsFromV2AppDefinition(definition),
1759
+ details: createOptions
1760
+ },
1761
+ title: definition.title,
1762
+ version: definition.version,
1763
+ icon: this.getIconFromDefinition(definition, version),
1764
+ caption: definition.description,
1765
+ fdc3: version === "2.0" ? { ...definition, definitionVersion: "2.0" } : undefined,
1766
+ };
1767
+ const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"];
1768
+ if (!ioConnectDefinition) {
1769
+ return baseApplicationData;
1770
+ }
1771
+ const ioDefinitionDecodeRes = glue42HostManifestsBrowserDecoder.run(ioConnectDefinition);
1772
+ if (!ioDefinitionDecodeRes.ok) {
1773
+ throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(ioDefinitionDecodeRes.error)}`);
1774
+ }
1775
+ if (!Object.keys(ioDefinitionDecodeRes.result).length) {
1776
+ return baseApplicationData;
1777
+ }
1778
+ return this.mergeBaseAppDataWithGlueManifest(baseApplicationData, ioDefinitionDecodeRes.result);
1779
+ }
1780
+ parseToDesktopAppConfig(definition) {
1781
+ const { isFdc3, version } = this.isFdc3Definition(definition);
1782
+ if (!isFdc3) {
1783
+ throw new Error("The passed definition is not FDC3");
1784
+ }
1785
+ const decodeRes = allDefinitionsDecoder.run(definition);
1786
+ if (!decodeRes.ok) {
1787
+ throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`);
1788
+ }
1789
+ if (version === "1.2") {
1790
+ const fdc3v1Definition = definition;
1791
+ return {
1792
+ name: fdc3v1Definition.appId,
1793
+ type: "window",
1794
+ details: {
1795
+ url: this.getUrl(definition, version)
1796
+ },
1797
+ version: fdc3v1Definition.version,
1798
+ title: fdc3v1Definition.title,
1799
+ tooltip: fdc3v1Definition.tooltip,
1800
+ caption: fdc3v1Definition.description,
1801
+ icon: fdc3v1Definition.icons?.[0].icon,
1802
+ intents: fdc3v1Definition.intents,
1803
+ customProperties: {
1804
+ manifestType: fdc3v1Definition.manifestType,
1805
+ images: fdc3v1Definition.images,
1806
+ contactEmail: fdc3v1Definition.contactEmail,
1807
+ supportEmail: fdc3v1Definition.supportEmail,
1808
+ publisher: fdc3v1Definition.publisher,
1809
+ icons: fdc3v1Definition.icons,
1810
+ customConfig: fdc3v1Definition.customConfig
1811
+ }
1812
+ };
1813
+ }
1814
+ const fdc3v2Definition = definition;
1815
+ const desktopDefinition = {
1816
+ name: fdc3v2Definition.appId,
1817
+ type: this.fdc3ToDesktopDefinitionType[fdc3v2Definition.type],
1818
+ details: fdc3v2Definition.details,
1819
+ version: fdc3v2Definition.version,
1820
+ title: fdc3v2Definition.title,
1821
+ tooltip: fdc3v2Definition.tooltip,
1822
+ caption: fdc3v2Definition.description,
1823
+ icon: this.getIconFromDefinition(fdc3v2Definition, "2.0"),
1824
+ intents: this.getIntentsFromV2AppDefinition(fdc3v2Definition),
1825
+ fdc3: { ...fdc3v2Definition, definitionVersion: "2.0" }
1826
+ };
1827
+ const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"];
1828
+ if (!ioConnectDefinition) {
1829
+ return desktopDefinition;
1830
+ }
1831
+ if (typeof ioConnectDefinition !== "object" || Array.isArray(ioConnectDefinition)) {
1832
+ throw new Error(`Invalid '${definition.hostManifests.ioConnect ? "hostManifests.ioConnect" : "hostManifests['Glue42']"}' key`);
1833
+ }
1834
+ return this.mergeDesktopConfigWithGlueManifest(desktopDefinition, ioConnectDefinition);
1835
+ }
1836
+ getUserPropertiesFromDefinition(definition, version) {
1837
+ if (version === "1.2") {
1838
+ return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key)));
1839
+ }
1840
+ return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key) && !fdc3v2AppProps.includes(key)));
1841
+ }
1842
+ getUrl(definition, version) {
1843
+ let url;
1844
+ if (version === "1.2") {
1845
+ const parsedManifest = JSON.parse(definition.manifest);
1846
+ url = parsedManifest.details?.url || parsedManifest.url;
1847
+ }
1848
+ else {
1849
+ url = definition.details?.url;
1850
+ }
1851
+ if (!url || typeof url !== "string") {
1852
+ throw new Error(`Invalid FDC3 ${version} definition. Provide valid 'url' under '${version === "1.2" ? "manifest" : "details"}' key`);
1853
+ }
1854
+ return url;
1855
+ }
1856
+ getIntentsFromV2AppDefinition(definition) {
1857
+ const fdc3Intents = definition.interop?.intents?.listensFor;
1858
+ if (!fdc3Intents) {
1859
+ return;
1860
+ }
1861
+ const intents = Object.entries(fdc3Intents).map((fdc3Intent) => {
1862
+ const [intentName, intentData] = fdc3Intent;
1863
+ return {
1864
+ name: intentName,
1865
+ ...intentData
1866
+ };
1867
+ });
1868
+ return intents;
1869
+ }
1870
+ getIconFromDefinition(definition, version) {
1871
+ if (version === "1.2") {
1872
+ return definition.icons?.find((iconDef) => iconDef.icon)?.icon || undefined;
1873
+ }
1874
+ return definition.icons?.find((iconDef) => iconDef.src)?.src || undefined;
1875
+ }
1876
+ mergeBaseAppDataWithGlueManifest(baseAppData, hostManifestDefinition) {
1877
+ let baseApplicationDefinition = baseAppData;
1878
+ if (hostManifestDefinition.customProperties) {
1879
+ baseApplicationDefinition.userProperties = { ...baseAppData.userProperties, ...hostManifestDefinition.customProperties };
1880
+ }
1881
+ if (hostManifestDefinition.details) {
1882
+ const details = { ...baseAppData.createOptions, ...hostManifestDefinition.details };
1883
+ baseApplicationDefinition.createOptions = details;
1884
+ baseApplicationDefinition.userProperties.details = details;
1885
+ }
1886
+ if (Array.isArray(hostManifestDefinition.intents)) {
1887
+ baseApplicationDefinition.userProperties.intents = (baseApplicationDefinition.userProperties.intents || []).concat(hostManifestDefinition.intents);
1888
+ }
1889
+ baseApplicationDefinition = { ...baseApplicationDefinition, ...hostManifestDefinition };
1890
+ delete baseApplicationDefinition.details;
1891
+ delete baseApplicationDefinition.intents;
1892
+ return baseApplicationDefinition;
1893
+ }
1894
+ mergeDesktopConfigWithGlueManifest(config, desktopDefinition) {
1895
+ const appConfig = Object.assign({}, config, desktopDefinition, { details: { ...config.details, ...desktopDefinition.details } });
1896
+ if (Array.isArray(desktopDefinition.intents)) {
1897
+ appConfig.intents = (config.intents || []).concat(desktopDefinition.intents);
1898
+ }
1899
+ return appConfig;
1900
+ }
1901
+ }
1902
+
1903
+ const decoders$1 = {
1904
+ common: {
1905
+ nonEmptyStringDecoder: nonEmptyStringDecoder$4,
1906
+ nonNegativeNumberDecoder
1907
+ },
1908
+ fdc3: {
1909
+ allDefinitionsDecoder,
1910
+ v1DefinitionDecoder,
1911
+ v2DefinitionDecoder
1912
+ }
1913
+ };
1914
+
1915
+ var INTENTS_ERRORS;
1916
+ (function (INTENTS_ERRORS) {
1917
+ INTENTS_ERRORS["USER_CANCELLED"] = "User Closed Intents Resolver UI without choosing a handler";
1918
+ INTENTS_ERRORS["CALLER_NOT_DEFINED"] = "Caller Id is not defined";
1919
+ INTENTS_ERRORS["TIMEOUT_HIT"] = "Timeout hit";
1920
+ INTENTS_ERRORS["INTENT_NOT_FOUND"] = "Cannot find Intent";
1921
+ INTENTS_ERRORS["HANDLER_NOT_FOUND"] = "Cannot find Intent Handler";
1922
+ INTENTS_ERRORS["TARGET_INSTANCE_UNAVAILABLE"] = "Cannot start Target Instance";
1923
+ INTENTS_ERRORS["INTENT_DELIVERY_FAILED"] = "Target Instance did not add a listener";
1924
+ INTENTS_ERRORS["RESOLVER_UNAVAILABLE"] = "Intents Resolver UI unavailable";
1925
+ INTENTS_ERRORS["RESOLVER_TIMEOUT"] = "User did not choose a handler";
1926
+ INTENTS_ERRORS["INVALID_RESOLVER_RESPONSE"] = "Intents Resolver UI returned invalid response";
1927
+ INTENTS_ERRORS["INTENT_HANDLER_REJECTION"] = "Intent Handler function processing the raised intent threw an error or rejected the promise it returned";
1928
+ })(INTENTS_ERRORS || (INTENTS_ERRORS = {}));
1929
+
1930
+ let IoC$1 = class IoC {
1931
+ _fdc3;
1932
+ _decoders = decoders$1;
1933
+ _errors = {
1934
+ intents: INTENTS_ERRORS
1935
+ };
1936
+ get fdc3() {
1937
+ if (!this._fdc3) {
1938
+ this._fdc3 = new FDC3Service().toApi();
1939
+ }
1940
+ return this._fdc3;
1941
+ }
1942
+ get decoders() {
1943
+ return this._decoders;
1944
+ }
1945
+ get errors() {
1946
+ return this._errors;
1947
+ }
1948
+ };
1949
+
1950
+ const ioc = new IoC$1();
1951
+ ioc.fdc3;
1952
+ const decoders = ioc.decoders;
1953
+ ioc.errors;
1954
+
1955
+ const { nonEmptyStringDecoder: nonEmptyStringDecoder$3 } = decoders.common;
1956
+ const requestMessageTypeDecoder = oneOf$1(constant$1("addContextListenerRequest"), constant$1("addEventListenerRequest"), constant$1("addIntentListenerRequest"), constant$1("broadcastRequest"), constant$1("contextListenerUnsubscribeRequest"), constant$1("createPrivateChannelRequest"), constant$1("eventListenerUnsubscribeRequest"), constant$1("findInstancesRequest"), constant$1("findIntentRequest"), constant$1("findIntentsByContextRequest"), constant$1("getAppMetadataRequest"), constant$1("getCurrentChannelRequest"), constant$1("getCurrentContextRequest"), constant$1("getInfoRequest"), constant$1("getOrCreateChannelRequest"), constant$1("getUserChannelsRequest"), constant$1("heartbeatAcknowledgementRequest"), constant$1("intentListenerUnsubscribeRequest"), constant$1("intentResultRequest"), constant$1("joinUserChannelRequest"), constant$1("leaveCurrentChannelRequest"), constant$1("openRequest"), constant$1("privateChannelAddEventListenerRequest"), constant$1("privateChannelDisconnectRequest"), constant$1("privateChannelUnsubscribeEventListenerRequest"), constant$1("raiseIntentForContextRequest"), constant$1("raiseIntentRequest"));
1957
+ const responseMessageTypeDecoder = oneOf$1(constant$1("addContextListenerResponse"), constant$1("addEventListenerResponse"), constant$1("addIntentListenerResponse"), constant$1("broadcastResponse"), constant$1("contextListenerUnsubscribeResponse"), constant$1("createPrivateChannelResponse"), constant$1("eventListenerUnsubscribeResponse"), constant$1("findInstancesResponse"), constant$1("findIntentResponse"), constant$1("findIntentsByContextResponse"), constant$1("getAppMetadataResponse"), constant$1("getCurrentChannelResponse"), constant$1("getCurrentContextResponse"), constant$1("getInfoResponse"), constant$1("getOrCreateChannelResponse"), constant$1("getUserChannelsResponse"), constant$1("intentListenerUnsubscribeResponse"), constant$1("intentResultResponse"), constant$1("joinUserChannelResponse"), constant$1("leaveCurrentChannelResponse"), constant$1("openResponse"), constant$1("privateChannelAddEventListenerResponse"), constant$1("privateChannelDisconnectResponse"), constant$1("privateChannelUnsubscribeEventListenerResponse"), constant$1("raiseIntentForContextResponse"), constant$1("raiseIntentResponse"), constant$1("raiseIntentResultResponse"));
1958
+ const webConnectionProtocolMessageTypeDecoder = oneOf$1(constant$1("WCP1Hello"), constant$1("WCP2LoadUrl"), constant$1("WCP3Handshake"), constant$1("WCP4ValidateAppIdentity"), constant$1("WCP5ValidateAppIdentityFailedResponse"), constant$1("WCP5ValidateAppIdentityResponse"), constant$1("WCP6Goodbye"));
1959
+ const appIdentifierDecoder = object$1({
1960
+ appId: nonEmptyStringDecoder$3,
1961
+ desktopAgent: optional$1(nonEmptyStringDecoder$3),
1962
+ instanceId: optional$1(nonEmptyStringDecoder$3)
1963
+ });
1964
+ const appRequestMetaDecoder = object$1({
1965
+ requestUuid: nonEmptyStringDecoder$3,
1966
+ timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
1967
+ source: optional$1(appIdentifierDecoder)
1968
+ });
1969
+ const responseMetaDecoder = object$1({
1970
+ requestUuid: nonEmptyStringDecoder$3,
1971
+ responseUuid: nonEmptyStringDecoder$3,
1972
+ source: optional$1(appIdentifierDecoder),
1973
+ timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
1974
+ });
1975
+ const connectionStepMetaDecoder = object$1({
1976
+ connectionAttemptUuid: nonEmptyStringDecoder$3,
1977
+ timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
1978
+ });
1979
+ object$1({
1980
+ type: webConnectionProtocolMessageTypeDecoder,
1981
+ meta: connectionStepMetaDecoder,
1982
+ payload: anyJson$1()
1983
+ });
1984
+ const contextDecoder = object$1({
1985
+ type: nonEmptyStringDecoder$3,
1986
+ name: optional$1(nonEmptyStringDecoder$3),
1987
+ id: optional$1(anyJson$1()),
1988
+ });
1989
+ const responsePayloadErrorDecoder = oneOf$1(constant$1("AccessDenied"), constant$1("CreationFailed"), constant$1("MalformedContext"), constant$1("NoChannelFound"), constant$1("AppNotFound"), constant$1("AppTimeout"), constant$1("DesktopAgentNotFound"), constant$1("ErrorOnLaunch"), constant$1("ResolverUnavailable"), constant$1("IntentDeliveryFailed"), constant$1("NoAppsFound"), constant$1("ResolverTimeout"), constant$1("TargetAppUnavailable"), constant$1("TargetInstanceUnavailable"), constant$1("UserCancelledResolution"), constant$1("IntentHandlerRejected"), constant$1("NoResultReturned"), constant$1("AgentDisconnected"), constant$1("NotConnectedToBridge"), constant$1("ResponseToBridgeTimedOut"), constant$1("MalformedMessage"));
1990
+ const fluffyErrorDecoder = oneOf$1(constant$1("MalformedContext"), constant$1("DesktopAgentNotFound"), constant$1("ResolverUnavailable"), constant$1("IntentDeliveryFailed"), constant$1("NoAppsFound"), constant$1("ResolverTimeout"), constant$1("TargetAppUnavailable"), constant$1("TargetInstanceUnavailable"), constant$1("UserCancelledResolution"));
1991
+ const wcp1HelloPayloadDecoder = object$1({
1992
+ actualUrl: nonEmptyStringDecoder$3,
1993
+ channelSelector: optional$1(boolean$1()),
1994
+ fdc3Version: nonEmptyStringDecoder$3,
1995
+ identityUrl: nonEmptyStringDecoder$3,
1996
+ resolver: optional$1(boolean$1())
1997
+ });
1998
+ const wcp1HelloMetaDecoder = object$1({
1999
+ connectionAttemptUuid: nonEmptyStringDecoder$3,
2000
+ timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2001
+ });
2002
+ const wcp1HelloDecoder = object$1({
2003
+ type: constant$1("WCP1Hello"),
2004
+ meta: wcp1HelloMetaDecoder,
2005
+ payload: wcp1HelloPayloadDecoder
2006
+ });
2007
+ const wcp3HandshakePayloadChannelSelectorUrlDecoder = oneOf$1(boolean$1(), nonEmptyStringDecoder$3);
2008
+ const wcp3HandshakePayloadIntentResolverUrlDecoder = oneOf$1(boolean$1(), nonEmptyStringDecoder$3);
2009
+ const wcp3HandshakePayloadDecoder = object$1({
2010
+ channelSelectorUrl: wcp3HandshakePayloadChannelSelectorUrlDecoder,
2011
+ fdc3Version: nonEmptyStringDecoder$3,
2012
+ intentResolverUrl: wcp3HandshakePayloadIntentResolverUrlDecoder
2013
+ });
2014
+ object$1({
2015
+ type: constant$1("WCP3Handshake"),
2016
+ meta: wcp1HelloMetaDecoder,
2017
+ payload: wcp3HandshakePayloadDecoder
2018
+ });
2019
+ const wcp4ValidateAppIdentityPayloadDecoder = object$1({
2020
+ actualUrl: nonEmptyStringDecoder$3,
2021
+ identityUrl: nonEmptyStringDecoder$3,
2022
+ instanceId: optional$1(nonEmptyStringDecoder$3),
2023
+ instanceUuid: optional$1(nonEmptyStringDecoder$3)
2024
+ });
2025
+ const wcp4ValidateAppIdentityDecoder = object$1({
2026
+ type: constant$1("WCP4ValidateAppIdentity"),
2027
+ meta: wcp1HelloMetaDecoder,
2028
+ payload: wcp4ValidateAppIdentityPayloadDecoder
2029
+ });
2030
+ const wcp5ValidateAppIdentityFailedResponsePayloadDecoder = object$1({
2031
+ message: optional$1(nonEmptyStringDecoder$3)
2032
+ });
2033
+ object$1({
2034
+ type: constant$1("WCP5ValidateAppIdentityFailedResponse"),
2035
+ meta: wcp1HelloMetaDecoder,
2036
+ payload: wcp5ValidateAppIdentityFailedResponsePayloadDecoder
2037
+ });
2038
+ const wcp6GoodbyeRequestDecoder = object$1({
2039
+ type: constant$1("WCP6Goodbye"),
2040
+ meta: connectionStepMetaDecoder,
2041
+ payload: anyJson$1()
2042
+ });
2043
+ const iconDecoder = object$1({
2044
+ src: nonEmptyStringDecoder$3,
2045
+ size: optional$1(nonEmptyStringDecoder$3),
2046
+ type: optional$1(nonEmptyStringDecoder$3)
2047
+ });
2048
+ const imageDecoder = object$1({
2049
+ src: nonEmptyStringDecoder$3,
2050
+ size: optional$1(nonEmptyStringDecoder$3),
2051
+ type: optional$1(nonEmptyStringDecoder$3),
2052
+ label: optional$1(nonEmptyStringDecoder$3),
2053
+ });
2054
+ const appMetadataDecoder = object$1({
2055
+ appId: nonEmptyStringDecoder$3,
2056
+ description: optional$1(nonEmptyStringDecoder$3),
2057
+ desktopAgent: optional$1(nonEmptyStringDecoder$3),
2058
+ icons: optional$1(array$1(iconDecoder)),
2059
+ instanceId: optional$1(nonEmptyStringDecoder$3),
2060
+ instanceMetadata: optional$1(anyJson$1()),
2061
+ name: optional$1(nonEmptyStringDecoder$3),
2062
+ resultType: optional$1(nonEmptyStringDecoder$3),
2063
+ screenshots: optional$1(array$1(imageDecoder)),
2064
+ title: optional$1(nonEmptyStringDecoder$3),
2065
+ tooltip: optional$1(nonEmptyStringDecoder$3),
2066
+ version: optional$1(nonEmptyStringDecoder$3),
2067
+ });
2068
+ const optionalFeaturesDecoder = object$1({
2069
+ DesktopAgentBridging: boolean$1(),
2070
+ OriginatingAppMetadata: boolean$1(),
2071
+ UserChannelMembershipAPIs: boolean$1()
2072
+ });
2073
+ const implementationMetadataDecoder = object$1({
2074
+ appMetadata: appMetadataDecoder,
2075
+ fdc3Version: nonEmptyStringDecoder$3,
2076
+ optionalFeatures: optionalFeaturesDecoder,
2077
+ provider: nonEmptyStringDecoder$3,
2078
+ providerVersion: optional$1(nonEmptyStringDecoder$3)
2079
+ });
2080
+ const wcp5ValidateAppIdentitySuccessResponsePayloadDecoder = object$1({
2081
+ appId: nonEmptyStringDecoder$3,
2082
+ implementationMetadata: implementationMetadataDecoder,
2083
+ instanceId: nonEmptyStringDecoder$3,
2084
+ instanceUuid: nonEmptyStringDecoder$3
2085
+ });
2086
+ object$1({
2087
+ type: constant$1("WCP5ValidateAppIdentityResponse"),
2088
+ meta: wcp1HelloMetaDecoder,
2089
+ payload: wcp5ValidateAppIdentitySuccessResponsePayloadDecoder
2090
+ });
2091
+
2092
+ const { nonEmptyStringDecoder: nonEmptyStringDecoder$2 } = decoders.common;
2093
+ const addContextListenerRequestMetaDecoder = object$1({
2094
+ requestUuid: nonEmptyStringDecoder$2,
2095
+ source: optional$1(appIdentifierDecoder),
2096
+ timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2097
+ });
2098
+ const addContextListenerRequestPayloadDecoder = object$1({
2099
+ channelId: optional$1(nonEmptyStringDecoder$2),
2100
+ contextType: optional$1(nonEmptyStringDecoder$2)
2101
+ });
2102
+ const addContextListenerRequestDecoder = object$1({
2103
+ type: constant$1("addContextListenerRequest"),
2104
+ meta: addContextListenerRequestMetaDecoder,
2105
+ payload: addContextListenerRequestPayloadDecoder
2106
+ });
2107
+ const addContextListenerResponseMetaDecoder = object$1({
2108
+ requestUuid: nonEmptyStringDecoder$2,
2109
+ responseUuid: nonEmptyStringDecoder$2,
2110
+ source: optional$1(appIdentifierDecoder),
2111
+ timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2112
+ });
2113
+ const addEventListenerTypeDecoder = oneOf$1(constant$1("USER_CHANNEL_CHANGED"));
2114
+ const addEventListenerRequestPayloadDecoder = object$1({
2115
+ type: optional$1(addEventListenerTypeDecoder)
2116
+ });
2117
+ const addEventListenerRequestDecoder = object$1({
2118
+ type: constant$1("addEventListenerRequest"),
2119
+ meta: addContextListenerRequestMetaDecoder,
2120
+ payload: addEventListenerRequestPayloadDecoder
2121
+ });
2122
+ const addEventListenerResponsePayloadDecoder = object$1({
2123
+ error: optional$1(responsePayloadErrorDecoder),
2124
+ listenerUUID: optional$1(nonEmptyStringDecoder$2)
2125
+ });
2126
+ const addEventListenerResponseDecoder = object$1({
2127
+ type: constant$1("addEventListenerResponse"),
2128
+ meta: addContextListenerResponseMetaDecoder,
2129
+ payload: addEventListenerResponsePayloadDecoder
2130
+ });
2131
+ const purpleErrorDecoder = oneOf$1(constant$1("AccessDenied"), constant$1("CreationFailed"), constant$1("MalformedContext"), constant$1("NoChannelFound"));
2132
+ const addContextListenerResponsePayloadDecoder = object$1({
2133
+ error: optional$1(purpleErrorDecoder),
2134
+ listenerUUID: optional$1(nonEmptyStringDecoder$2)
2135
+ });
2136
+ const addContextListenerResponseDecoder = object$1({
2137
+ type: constant$1("addContextListenerResponse"),
2138
+ meta: addContextListenerResponseMetaDecoder,
2139
+ payload: addContextListenerResponsePayloadDecoder
2140
+ });
2141
+ const broadcastRequestPayloadDecoder = object$1({
2142
+ channelId: nonEmptyStringDecoder$2,
2143
+ context: contextDecoder
2144
+ });
2145
+ const broadcastRequestDecoder = object$1({
2146
+ type: constant$1("broadcastRequest"),
2147
+ meta: appRequestMetaDecoder,
2148
+ payload: broadcastRequestPayloadDecoder
2149
+ });
2150
+ const broadcastResponsePayloadDecoder = object$1({
2151
+ error: optional$1(responsePayloadErrorDecoder)
2152
+ });
2153
+ const broadcastResponseDecoder = object$1({
2154
+ type: constant$1("broadcastResponse"),
2155
+ meta: responseMetaDecoder,
2156
+ payload: broadcastResponsePayloadDecoder
2157
+ });
2158
+ const channelTypeDecoder = oneOf$1(constant$1("app"), constant$1("user"), constant$1("private"));
2159
+ const displayMetadataDecoder = object$1({
2160
+ color: optional$1(nonEmptyStringDecoder$2),
2161
+ glyph: optional$1(nonEmptyStringDecoder$2),
2162
+ name: optional$1(nonEmptyStringDecoder$2),
2163
+ });
2164
+ const channelDecoder = object$1({
2165
+ id: nonEmptyStringDecoder$2,
2166
+ type: channelTypeDecoder,
2167
+ displayMetadata: optional$1(displayMetadataDecoder)
2168
+ });
2169
+ const contextListenerUnsubscribeRequestPayloadDecoder = object$1({
2170
+ listenerUUID: nonEmptyStringDecoder$2
2171
+ });
2172
+ const contextListenerUnsubscribeRequestDecoder = object$1({
2173
+ type: constant$1("contextListenerUnsubscribeRequest"),
2174
+ meta: addContextListenerRequestMetaDecoder,
2175
+ payload: contextListenerUnsubscribeRequestPayloadDecoder
2176
+ });
2177
+ const contextListenerUnsubscribeResponseDecoder = object$1({
2178
+ type: constant$1("contextListenerUnsubscribeResponse"),
2179
+ meta: addContextListenerResponseMetaDecoder,
2180
+ payload: broadcastResponsePayloadDecoder
2181
+ });
2182
+ const createPrivateChannelRequestDecoder = object$1({
2183
+ type: constant$1("createPrivateChannelRequest"),
2184
+ meta: addContextListenerRequestMetaDecoder,
2185
+ payload: anyJson$1()
2186
+ });
2187
+ const createPrivateChannelResponsePayloadDecoder = object$1({
2188
+ error: optional$1(purpleErrorDecoder),
2189
+ privateChannel: optional$1(channelDecoder)
2190
+ });
2191
+ const createPrivateChannelResponseDecoder = object$1({
2192
+ type: constant$1("createPrivateChannelResponse"),
2193
+ meta: addContextListenerResponseMetaDecoder,
2194
+ payload: createPrivateChannelResponsePayloadDecoder
2195
+ });
2196
+ const eventListenerUnsubscribeRequestPayloadDecoder = object$1({
2197
+ listenerUUID: nonEmptyStringDecoder$2
2198
+ });
2199
+ const eventListenerUnsubscribeRequestDecoder = object$1({
2200
+ type: constant$1("eventListenerUnsubscribeRequest"),
2201
+ meta: addContextListenerRequestMetaDecoder,
2202
+ payload: eventListenerUnsubscribeRequestPayloadDecoder
2203
+ });
2204
+ const eventListenerUnsubscribeResponseDecoder = object$1({
2205
+ type: constant$1("eventListenerUnsubscribeResponse"),
2206
+ meta: addContextListenerResponseMetaDecoder,
2207
+ payload: broadcastResponsePayloadDecoder
2208
+ });
2209
+ const getCurrentChannelRequestDecoder = object$1({
2210
+ type: constant$1("getCurrentChannelRequest"),
2211
+ meta: addContextListenerRequestMetaDecoder,
2212
+ payload: anyJson$1()
2213
+ });
2214
+ const getCurrentChannelResponsePayloadDecoder = object$1({
2215
+ error: optional$1(responsePayloadErrorDecoder),
2216
+ channel: optional$1(channelDecoder)
2217
+ });
2218
+ const getCurrentChannelResponseDecoder = object$1({
2219
+ type: constant$1("getCurrentChannelResponse"),
2220
+ meta: addContextListenerResponseMetaDecoder,
2221
+ payload: getCurrentChannelResponsePayloadDecoder
2222
+ });
2223
+ const getCurrentContextRequestPayloadDecoder = object$1({
2224
+ channelId: nonEmptyStringDecoder$2,
2225
+ contextType: optional$1(nonEmptyStringDecoder$2)
2226
+ });
2227
+ const getCurrentContextRequestDecoder = object$1({
2228
+ type: constant$1("getCurrentContextRequest"),
2229
+ meta: addContextListenerRequestMetaDecoder,
2230
+ payload: getCurrentContextRequestPayloadDecoder
2231
+ });
2232
+ const getCurrentContextResponsePayloadDecoder = object$1({
2233
+ error: optional$1(purpleErrorDecoder),
2234
+ context: optional$1(contextDecoder)
2235
+ });
2236
+ const getCurrentContextResponseDecoder = object$1({
2237
+ type: constant$1("getCurrentContextResponse"),
2238
+ meta: addContextListenerResponseMetaDecoder,
2239
+ payload: getCurrentContextResponsePayloadDecoder
2240
+ });
2241
+ const getOrCreateChannelRequestPayloadDecoder = object$1({
2242
+ channelId: nonEmptyStringDecoder$2
2243
+ });
2244
+ const getOrCreateChannelRequestDecoder = object$1({
2245
+ type: constant$1("getOrCreateChannelRequest"),
2246
+ meta: addContextListenerRequestMetaDecoder,
2247
+ payload: getOrCreateChannelRequestPayloadDecoder
2248
+ });
2249
+ const getOrCreateChannelResponsePayloadDecoder = object$1({
2250
+ error: optional$1(purpleErrorDecoder),
2251
+ channel: optional$1(channelDecoder)
2252
+ });
2253
+ const getOrCreateChannelResponseDecoder = object$1({
2254
+ type: constant$1("getOrCreateChannelResponse"),
2255
+ meta: addContextListenerResponseMetaDecoder,
2256
+ payload: getOrCreateChannelResponsePayloadDecoder
2257
+ });
2258
+ const getUserChannelsRequestDecoder = object$1({
2259
+ type: constant$1("getUserChannelsRequest"),
2260
+ meta: addContextListenerRequestMetaDecoder,
2261
+ payload: anyJson$1()
2262
+ });
2263
+ const getUserChannelsResponsePayloadDecoder = object$1({
2264
+ error: optional$1(purpleErrorDecoder),
2265
+ userChannels: optional$1(array$1(channelDecoder))
2266
+ });
2267
+ const getUserChannelsResponseDecoder = object$1({
2268
+ type: constant$1("getUserChannelsResponse"),
2269
+ meta: addContextListenerResponseMetaDecoder,
2270
+ payload: getUserChannelsResponsePayloadDecoder
2271
+ });
2272
+ const joinUserChannelRequestPayloadDecoder = object$1({
2273
+ channelId: nonEmptyStringDecoder$2
2274
+ });
2275
+ const joinUserChannelRequestDecoder = object$1({
2276
+ type: constant$1("joinUserChannelRequest"),
2277
+ meta: addContextListenerRequestMetaDecoder,
2278
+ payload: joinUserChannelRequestPayloadDecoder
2279
+ });
2280
+ const joinUserChannelResponsePayloadDecoder = object$1({
2281
+ error: optional$1(purpleErrorDecoder)
2282
+ });
2283
+ const joinUserChannelResponseDecoder = object$1({
2284
+ type: constant$1("joinUserChannelResponse"),
2285
+ meta: addContextListenerResponseMetaDecoder,
2286
+ payload: joinUserChannelResponsePayloadDecoder
2287
+ });
2288
+ const leaveCurrentChannelRequestDecoder = object$1({
2289
+ type: constant$1("leaveCurrentChannelRequest"),
2290
+ meta: addContextListenerRequestMetaDecoder,
2291
+ payload: anyJson$1()
2292
+ });
2293
+ const leaveCurrentChannelResponsePayloadDecoder = object$1({
2294
+ error: optional$1(purpleErrorDecoder)
2295
+ });
2296
+ const leaveCurrentChannelResponseDecoder = object$1({
2297
+ type: constant$1("leaveCurrentChannelResponse"),
2298
+ meta: addContextListenerResponseMetaDecoder,
2299
+ payload: leaveCurrentChannelResponsePayloadDecoder
2300
+ });
2301
+ const privateChannelEventListenerTypesDecoder = oneOf$1(constant$1("addContextListener"), constant$1("unsubscribe"), constant$1("disconnect"));
2302
+ const privateChannelAddEventListenerRequestPayloadDecoder = object$1({
2303
+ listenerType: optional$1(privateChannelEventListenerTypesDecoder),
2304
+ privateChannelId: nonEmptyStringDecoder$2
2305
+ });
2306
+ const privateChannelAddEventListenerRequestDecoder = object$1({
2307
+ type: constant$1("privateChannelAddEventListenerRequest"),
2308
+ meta: addContextListenerRequestMetaDecoder,
2309
+ payload: privateChannelAddEventListenerRequestPayloadDecoder
2310
+ });
2311
+ const privateChannelAddEventListenerResponsePayloadDecoder = object$1({
2312
+ listenerUUID: optional$1(nonEmptyStringDecoder$2),
2313
+ error: optional$1(purpleErrorDecoder)
2314
+ });
2315
+ const privateChannelAddEventListenerResponseDecoder = object$1({
2316
+ type: constant$1("privateChannelAddEventListenerResponse"),
2317
+ meta: addContextListenerResponseMetaDecoder,
2318
+ payload: privateChannelAddEventListenerResponsePayloadDecoder
2319
+ });
2320
+ const privateChannelDisconnectRequestPayloadDecoder = object$1({
2321
+ channelId: nonEmptyStringDecoder$2
2322
+ });
2323
+ const privateChannelDisconnectRequestDecoder = object$1({
2324
+ type: constant$1("privateChannelDisconnectRequest"),
2325
+ meta: addContextListenerRequestMetaDecoder,
2326
+ payload: privateChannelDisconnectRequestPayloadDecoder
2327
+ });
2328
+ const privateChannelDisconnectResponseDecoder = object$1({
2329
+ type: constant$1("privateChannelDisconnectResponse"),
2330
+ meta: addContextListenerResponseMetaDecoder,
2331
+ payload: addContextListenerResponsePayloadDecoder
2332
+ });
2333
+ const privateChannelUnsubscribeEventListenerRequestPayloadDecoder = object$1({
2334
+ listenerUUID: nonEmptyStringDecoder$2
2335
+ });
2336
+ const privateChannelUnsubscribeEventListenerRequestDecoder = object$1({
2337
+ type: constant$1("privateChannelUnsubscribeEventListenerRequest"),
2338
+ meta: addContextListenerRequestMetaDecoder,
2339
+ payload: privateChannelUnsubscribeEventListenerRequestPayloadDecoder
2340
+ });
2341
+ const privateChannelUnsubscribeEventListenerResponseDecoder = object$1({
2342
+ type: constant$1("privateChannelUnsubscribeEventListenerResponse"),
2343
+ meta: addContextListenerResponseMetaDecoder,
2344
+ payload: broadcastResponsePayloadDecoder
2345
+ });
2346
+ const broadcastEventMetaDecoder = object$1({
2347
+ eventUuid: nonEmptyStringDecoder$2,
2348
+ timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2349
+ });
2350
+
2351
+ const { nonEmptyStringDecoder: nonEmptyStringDecoder$1 } = decoders.common;
2352
+ const findInstancesRequestPayloadDecoder = object$1({
2353
+ app: appIdentifierDecoder
2354
+ });
2355
+ const findInstancesRequestDecoder = object$1({
2356
+ type: constant$1("findInstancesRequest"),
2357
+ meta: addContextListenerRequestMetaDecoder,
2358
+ payload: findInstancesRequestPayloadDecoder
2359
+ });
2360
+ const getAppMetadataRequestPayloadDecoder = object$1({
2361
+ app: appIdentifierDecoder
2362
+ });
2363
+ const getAppMetadataRequestDecoder = object$1({
2364
+ type: constant$1("getAppMetadataRequest"),
2365
+ meta: addContextListenerRequestMetaDecoder,
2366
+ payload: getAppMetadataRequestPayloadDecoder
2367
+ });
2368
+ const getInfoRequestDecoder = object$1({
2369
+ type: constant$1("getInfoRequest"),
2370
+ meta: addContextListenerRequestMetaDecoder,
2371
+ payload: anyJson$1()
2372
+ });
2373
+ const openRequestPayloadDecoder = object$1({
2374
+ app: appIdentifierDecoder,
2375
+ context: optional$1(contextDecoder)
2376
+ });
2377
+ const openRequestDecoder = object$1({
2378
+ type: constant$1("openRequest"),
2379
+ meta: addContextListenerRequestMetaDecoder,
2380
+ payload: openRequestPayloadDecoder
2381
+ });
2382
+ const findInstancesErrorsDecoder = oneOf$1(constant$1("MalformedContext"), constant$1("DesktopAgentNotFound"), constant$1("ResolverUnavailable"), constant$1("IntentDeliveryFailed"), constant$1("NoAppsFound"), constant$1("ResolverTimeout"), constant$1("TargetAppUnavailable"), constant$1("TargetInstanceUnavailable"), constant$1("UserCancelledResolution"), constant$1("AgentDisconnected"), constant$1("NotConnectedToBridge"), constant$1("ResponseToBridgeTimedOut"), constant$1("MalformedMessage"));
2383
+ const findInstancesResponsePayloadDecoder = object$1({
2384
+ error: optional$1(findInstancesErrorsDecoder),
2385
+ appIdentifiers: optional$1(array$1(appMetadataDecoder))
2386
+ });
2387
+ const findInstancesResponseDecoder = object$1({
2388
+ type: constant$1("findInstancesResponse"),
2389
+ meta: addContextListenerResponseMetaDecoder,
2390
+ payload: findInstancesResponsePayloadDecoder
2391
+ });
2392
+ const getAppMetadataResponsePayloadDecoder = object$1({
2393
+ error: optional$1(findInstancesErrorsDecoder),
2394
+ appMetadata: optional$1(appMetadataDecoder)
2395
+ });
2396
+ const getAppMetadataResponseDecoder = object$1({
2397
+ type: constant$1("getAppMetadataResponse"),
2398
+ meta: addContextListenerResponseMetaDecoder,
2399
+ payload: getAppMetadataResponsePayloadDecoder
2400
+ });
2401
+ const getInfoResponsePayloadDecoder = object$1({
2402
+ error: optional$1(responsePayloadErrorDecoder),
2403
+ implementationMetadata: optional$1(implementationMetadataDecoder)
2404
+ });
2405
+ const getInfoResponseDecoder = object$1({
2406
+ type: constant$1("getInfoResponse"),
2407
+ meta: addContextListenerResponseMetaDecoder,
2408
+ payload: getInfoResponsePayloadDecoder
2409
+ });
2410
+ const openErrorResponsePayloadDecoder = oneOf$1(constant$1("MalformedContext"), constant$1("AppNotFound"), constant$1("AppTimeout"), constant$1("DesktopAgentNotFound"), constant$1("ErrorOnLaunch"), constant$1("ResolverUnavailable"), constant$1("AgentDisconnected"), constant$1("NotConnectedToBridge"), constant$1("ResponseToBridgeTimedOut"), constant$1("MalformedMessage"));
2411
+ const openResponsePayloadDecoder = object$1({
2412
+ error: optional$1(openErrorResponsePayloadDecoder),
2413
+ appIdentifier: optional$1(appIdentifierDecoder)
2414
+ });
2415
+ const openResponseDecoder = object$1({
2416
+ type: constant$1("openResponse"),
2417
+ meta: addContextListenerResponseMetaDecoder,
2418
+ payload: openResponsePayloadDecoder
2419
+ });
2420
+ const heartbeatAcknowledgementRequestPayloadDecoder = object$1({
2421
+ heartbeatEventUuid: nonEmptyStringDecoder$1
2422
+ });
2423
+ const heartbeatAcknowledgementRequestDecoder = object$1({
2424
+ type: constant$1("heartbeatAcknowledgementRequest"),
2425
+ meta: addContextListenerRequestMetaDecoder,
2426
+ payload: heartbeatAcknowledgementRequestPayloadDecoder
2427
+ });
2428
+ const heartbeatEventPayloadDecoder = anyJson$1();
2429
+ const heartbeatEventDecoder = object$1({
2430
+ type: constant$1("heartbeatEvent"),
2431
+ meta: broadcastEventMetaDecoder,
2432
+ payload: heartbeatEventPayloadDecoder
2433
+ });
2434
+
2435
+ class ApplicationsController {
2436
+ logger;
2437
+ operations = {
2438
+ findInstancesRequest: { requestType: "findInstancesRequest", requestDecoder: findInstancesRequestDecoder, responseType: "findInstancesResponse", responseDecoder: findInstancesResponseDecoder, execute: this.handleFindInstancesRequest.bind(this) },
2439
+ getAppMetadataRequest: { requestType: "getAppMetadataRequest", requestDecoder: getAppMetadataRequestDecoder, responseType: "getAppMetadataResponse", responseDecoder: getAppMetadataResponseDecoder, execute: this.handleGetAppMetadataRequest.bind(this) },
2440
+ getInfoRequest: { requestType: "getInfoRequest", requestDecoder: getInfoRequestDecoder, responseType: "getInfoResponse", responseDecoder: getInfoResponseDecoder, execute: this.handleGetInfoRequest.bind(this) },
2441
+ openRequest: { requestType: "openRequest", requestDecoder: openRequestDecoder, responseType: "openResponse", responseDecoder: openResponseDecoder, execute: this.handleOpenRequest.bind(this) },
2442
+ heartbeatAcknowledgementRequest: { requestType: "heartbeatAcknowledgementRequest", requestDecoder: heartbeatAcknowledgementRequestDecoder, responseType: "heartbeatEvent", responseDecoder: heartbeatEventDecoder, execute: this.handleHeartbeatAcknowledgementRequest.bind(this) }
2443
+ };
2444
+ constructor(logger) {
2445
+ this.logger = logger;
2446
+ }
2447
+ async handleControl(request) {
2448
+ const operation = this.operations[request.type];
2449
+ const responseUuid = nanoid(10);
2450
+ if (!operation) {
2451
+ this.logger?.error(`Controller cannot perform unsupported message: ${JSON.stringify(request)}`);
2452
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received unsupported message type: ${request.type} for request: ${JSON.stringify(request)}` } });
2453
+ }
2454
+ this.logger?.info(`Received request: ${JSON.stringify(request)}`);
2455
+ const { requestDecoder, responseDecoder, execute } = operation;
2456
+ const decodedRequest = requestDecoder.run(request);
2457
+ if (!decodedRequest.ok) {
2458
+ this.logger?.error(`Received invalid request: ${JSON.stringify(request)}`);
2459
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received invalid request message. Reason: ${decodedRequest.error.message}` } });
2460
+ }
2461
+ this.logger?.info(`Handling ${request.type} request: ${JSON.stringify(request)}`);
2462
+ let payload;
2463
+ try {
2464
+ payload = await execute(request);
2465
+ }
2466
+ catch (error) {
2467
+ payload = { error: typeof error === "string" ? error : error.message };
2468
+ }
2469
+ this.logger?.info(`Execution logic for ${request.type} completed. Received payload: ${JSON.stringify(payload)}`);
2470
+ const response = this.decorateResponse({ request, payload, responseUuid });
2471
+ const decodedResponse = responseDecoder.run(response);
2472
+ if (!decodedResponse.ok) {
2473
+ this.logger?.error(`Invalid response type ${response.type}. Error: ${JSON.stringify(decodedResponse.error)}`);
2474
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received invalid response message. Reason: ${decodedResponse.error}` } });
2475
+ }
2476
+ this.logger?.info(`Returning response: ${JSON.stringify(response)}`);
2477
+ return response;
2478
+ }
2479
+ async handleFindInstancesRequest({ payload }) {
2480
+ const appIdentifiers = await window.fdc3?.findInstances(payload.app);
2481
+ return { appIdentifiers };
2482
+ }
2483
+ async handleGetAppMetadataRequest({ payload }) {
2484
+ const appMetadata = await window.fdc3?.getAppMetadata(payload.app);
2485
+ return { appMetadata };
2486
+ }
2487
+ async handleGetInfoRequest(request) {
2488
+ const implementationMetadata = await window.fdc3?.getInfo();
2489
+ return { implementationMetadata };
2490
+ }
2491
+ async handleOpenRequest({ payload }) {
2492
+ const appIdentifier = await window.fdc3?.open(payload.app, payload.context);
2493
+ return { appIdentifier };
2494
+ }
2495
+ async handleHeartbeatAcknowledgementRequest({ heartbeatEventUuid }) {
2496
+ return { alive: true, heartbeatEventUuid };
2497
+ }
2498
+ decorateResponse({ payload, request, responseUuid }) {
2499
+ return {
2500
+ type: this.operations[request.type].responseType,
2501
+ meta: {
2502
+ requestUuid: request.meta.requestUuid,
2503
+ responseUuid: responseUuid,
2504
+ source: request.meta.source,
2505
+ timestamp: new Date()
2506
+ },
2507
+ payload
2508
+ };
2509
+ }
2510
+ }
2511
+
2512
+ var WCPMessageTypes;
2513
+ (function (WCPMessageTypes) {
2514
+ WCPMessageTypes["WCP1Hello"] = "WCP1Hello";
2515
+ WCPMessageTypes["WCP2LoadUrl"] = "WCP2LoadUrl";
2516
+ WCPMessageTypes["WCP3Handshake"] = "WCP3Handshake";
2517
+ WCPMessageTypes["WCP4ValidateAppIdentity"] = "WCP4ValidateAppIdentity";
2518
+ WCPMessageTypes["WCP5ValidateAppIdentityFailedResponse"] = "WCP5ValidateAppIdentityFailedResponse";
2519
+ WCPMessageTypes["WCP5ValidateAppIdentityResponse"] = "WCP5ValidateAppIdentityResponse";
2520
+ WCPMessageTypes["WCP6Goodbye"] = "WCP6Goodbye";
2521
+ })(WCPMessageTypes || (WCPMessageTypes = {}));
2522
+ const FDC3_READY_TIMEOUT = 120 * 1000;
2523
+ const DESKTOP_AGENT_NAME = "io.Connect Browser";
2524
+ const channelTypes = ["user", "app", "private"];
2525
+ const defaultChannelsProps = ["id", "type", "broadcast", "addContextListener", "getCurrentContext"];
2526
+
2527
+ var ChannelEventToTypeDictionary;
2528
+ (function (ChannelEventToTypeDictionary) {
2529
+ ChannelEventToTypeDictionary["USER_CHANNEL_CHANGED"] = "userChannelChanged";
2530
+ })(ChannelEventToTypeDictionary || (ChannelEventToTypeDictionary = {}));
2531
+ const privateChannelPrefix = "___privateFDC3Channel___";
2532
+
2533
+ class ChannelsController {
2534
+ sendBridgeMessage;
2535
+ logger;
2536
+ listenersCollection = {};
2537
+ privateChannelsCollection = {};
2538
+ operations = {
2539
+ addContextListenerRequest: { requestType: "addContextListenerRequest", requestDecoder: addContextListenerRequestDecoder, responseType: "addContextListenerResponse", responseDecoder: addContextListenerResponseDecoder, execute: this.handleAddContextListenerRequest.bind(this) },
2540
+ addEventListenerRequest: { requestType: "addEventListenerRequest", requestDecoder: addEventListenerRequestDecoder, responseType: "addEventListenerResponse", responseDecoder: addEventListenerResponseDecoder, execute: this.handleAddEventListenerRequest.bind(this) },
2541
+ broadcastRequest: { requestType: "broadcastRequest", responseType: "broadcastResponse", requestDecoder: broadcastRequestDecoder, responseDecoder: broadcastResponseDecoder, execute: this.handleBroadcastRequest.bind(this) },
2542
+ contextListenerUnsubscribeRequest: { requestType: "contextListenerUnsubscribeRequest", requestDecoder: contextListenerUnsubscribeRequestDecoder, responseType: "contextListenerUnsubscribeResponse", responseDecoder: contextListenerUnsubscribeResponseDecoder, execute: this.handleUnsubscribeRequest.bind(this) },
2543
+ createPrivateChannelRequest: { requestType: "createPrivateChannelRequest", requestDecoder: createPrivateChannelRequestDecoder, responseType: "createPrivateChannelResponse", responseDecoder: createPrivateChannelResponseDecoder, execute: this.handleCreatePrivateChannelRequest.bind(this) },
2544
+ eventListenerUnsubscribeRequest: { requestType: "eventListenerUnsubscribeRequest", requestDecoder: eventListenerUnsubscribeRequestDecoder, responseType: "eventListenerUnsubscribeResponse", responseDecoder: eventListenerUnsubscribeResponseDecoder, execute: this.handleUnsubscribeRequest.bind(this) },
2545
+ getCurrentChannelRequest: { requestType: "getCurrentChannelRequest", requestDecoder: getCurrentChannelRequestDecoder, responseType: "getCurrentChannelResponse", responseDecoder: getCurrentChannelResponseDecoder, execute: this.handleGetCurrentChannelRequest.bind(this) },
2546
+ getCurrentContextRequest: { requestType: "getCurrentContextRequest", requestDecoder: getCurrentContextRequestDecoder, responseType: "getCurrentContextResponse", responseDecoder: getCurrentContextResponseDecoder, execute: this.handleGetCurrentContextRequest.bind(this) },
2547
+ getOrCreateChannelRequest: { requestType: "getOrCreateChannelRequest", requestDecoder: getOrCreateChannelRequestDecoder, responseType: "getOrCreateChannelResponse", responseDecoder: getOrCreateChannelResponseDecoder, execute: this.handleGetOrCreateChannelRequest.bind(this) },
2548
+ getUserChannelsRequest: { requestType: "getUserChannelsRequest", requestDecoder: getUserChannelsRequestDecoder, responseType: "getUserChannelsResponse", responseDecoder: getUserChannelsResponseDecoder, execute: this.handleGetUserChannelsRequest.bind(this) },
2549
+ joinUserChannelRequest: { requestType: "joinUserChannelRequest", requestDecoder: joinUserChannelRequestDecoder, responseType: "joinUserChannelResponse", responseDecoder: joinUserChannelResponseDecoder, execute: this.handleJoinUserChannelRequest.bind(this) },
2550
+ leaveCurrentChannelRequest: { requestType: "leaveCurrentChannelRequest", requestDecoder: leaveCurrentChannelRequestDecoder, responseType: "leaveCurrentChannelResponse", responseDecoder: leaveCurrentChannelResponseDecoder, execute: this.handleLeaveCurrentChannel.bind(this) },
2551
+ privateChannelAddEventListenerRequest: { requestType: "privateChannelAddEventListenerRequest", requestDecoder: privateChannelAddEventListenerRequestDecoder, responseType: "privateChannelAddEventListenerResponse", responseDecoder: privateChannelAddEventListenerResponseDecoder, execute: this.handlePrivateChannelAddEventListenerRequest.bind(this) },
2552
+ privateChannelDisconnectRequest: { requestType: "privateChannelDisconnectRequest", requestDecoder: privateChannelDisconnectRequestDecoder, responseType: "privateChannelDisconnectResponse", responseDecoder: privateChannelDisconnectResponseDecoder, execute: this.handlePrivateChannelDisconnectRequest.bind(this) },
2553
+ privateChannelUnsubscribeEventListenerRequest: { requestType: "privateChannelUnsubscribeEventListenerRequest", requestDecoder: privateChannelUnsubscribeEventListenerRequestDecoder, responseType: "privateChannelUnsubscribeEventListenerResponse", responseDecoder: privateChannelUnsubscribeEventListenerResponseDecoder, execute: this.handlePrivateChannelUnsubscribeEventListenerRequest.bind(this) }
2554
+ };
2555
+ constructor(sendBridgeMessage, logger) {
2556
+ this.sendBridgeMessage = sendBridgeMessage;
2557
+ this.logger = logger;
2558
+ }
2559
+ async handleControl(request) {
2560
+ const operation = this.operations[request.type];
2561
+ const responseUuid = nanoid(10);
2562
+ if (!operation) {
2563
+ this.logger?.error(`Controller cannot perform unsupported message: ${JSON.stringify(request)}`);
2564
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received unsupported message type: ${request.type} for request: ${JSON.stringify(request)}` } });
2565
+ }
2566
+ this.logger?.info(`Received request: ${JSON.stringify(request)}`);
2567
+ const { requestDecoder, responseDecoder, execute } = operation;
2568
+ const decodedRequest = requestDecoder.run(request);
2569
+ if (!decodedRequest.ok) {
2570
+ this.logger?.error(`Received invalid request: ${JSON.stringify(request)}`);
2571
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received invalid request message. Reason: ${decodedRequest.error.message}` } });
2572
+ }
2573
+ this.logger?.info(`Handling ${request.type} request: ${JSON.stringify(request)}`);
2574
+ let payload;
2575
+ try {
2576
+ payload = await execute(request);
2577
+ }
2578
+ catch (error) {
2579
+ payload = { error: typeof error === "string" ? error : error.message };
2580
+ }
2581
+ this.logger?.info(`Execution logic for ${request.type} completed. Received payload: ${JSON.stringify(payload)}`);
2582
+ const response = this.decorateResponse({ request, payload, responseUuid });
2583
+ const decodedResponse = responseDecoder.run(response);
2584
+ if (!decodedResponse.ok) {
2585
+ this.logger?.error(`Invalid response type ${response.type}. Error: ${JSON.stringify(decodedResponse.error)}`);
2586
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received invalid response message. Reason: ${decodedResponse.error}` } });
2587
+ }
2588
+ this.logger?.info(`Returning response: ${JSON.stringify(response)}`);
2589
+ return response;
2590
+ }
2591
+ addPrivateChannel(privateChannel) {
2592
+ this.logger?.info(`addPrivateChannel called with channel id: ${privateChannel.id}, type: ${privateChannel.type}`);
2593
+ this.privateChannelsCollection[privateChannel.id] = privateChannel;
2594
+ }
2595
+ async handleAddContextListenerRequest({ payload }) {
2596
+ const listenerUUID = nanoid();
2597
+ const channel = payload.channelId ? await this.getChannelById(payload.channelId) : null;
2598
+ const handler = async (context, metadata) => {
2599
+ this.logger?.info(`addContextListener handler invoked with context: ${JSON.stringify(context)} and metadata: ${JSON.stringify(metadata)}`);
2600
+ const eventUuid = nanoid();
2601
+ const channelId = !payload.channelId || channel?.type === "user"
2602
+ ? (await window.fdc3?.getCurrentChannel())?.id ?? null
2603
+ : payload.channelId;
2604
+ const broadcastEventMsg = {
2605
+ type: "broadcastEvent",
2606
+ meta: {
2607
+ eventUuid,
2608
+ timestamp: new Date()
2609
+ },
2610
+ payload: {
2611
+ channelId,
2612
+ context,
2613
+ originatingApp: {
2614
+ appId: metadata?.source.appId ?? "",
2615
+ instanceId: metadata?.source.instanceId,
2616
+ desktopAgent: DESKTOP_AGENT_NAME
2617
+ }
2618
+ }
2619
+ };
2620
+ this.logger?.info(`Sending 'broadcastEvent' message: ${JSON.stringify(broadcastEventMsg)}`);
2621
+ this.sendBridgeMessage(broadcastEventMsg);
2622
+ };
2623
+ const addContextListenerInterfaceMsg = channel ? "channel '" + channel.id + "'" : "fdc3";
2624
+ this.logger?.info(`Adding context listener on ${addContextListenerInterfaceMsg} interface for context type ${payload.contextType ?? null}`);
2625
+ const listener = await (channel ?? window.fdc3)?.addContextListener(payload.contextType ?? null, handler);
2626
+ this.listenersCollection[listenerUUID] = listener;
2627
+ return { listenerUUID };
2628
+ }
2629
+ async getChannelById(id) {
2630
+ const privateChannel = this.privateChannelsCollection[id];
2631
+ if (privateChannel) {
2632
+ return privateChannel;
2633
+ }
2634
+ const channel = await window.fdc3?.getOrCreateChannel(id);
2635
+ return channel;
2636
+ }
2637
+ async handleAddEventListenerRequest({ payload }) {
2638
+ const listenerUUID = nanoid();
2639
+ const handler = (event) => {
2640
+ this.logger?.info(`addEventListener's callback invoked with event: ${JSON.stringify(event)}`);
2641
+ const eventUuid = nanoid();
2642
+ if (event.type !== "userChannelChanged") {
2643
+ return;
2644
+ }
2645
+ const response = {
2646
+ type: "channelChangedEvent",
2647
+ meta: {
2648
+ eventUuid,
2649
+ timestamp: new Date()
2650
+ },
2651
+ payload: {
2652
+ newChannelId: event.details.currentChannelId ?? null,
2653
+ }
2654
+ };
2655
+ this.logger?.info(`Sending 'channelChangedEvent' message: ${JSON.stringify(response)}`);
2656
+ this.sendBridgeMessage(response);
2657
+ };
2658
+ this.logger?.info(`Adding event listener for type ${payload.type ?? null} on fdc3 interface`);
2659
+ const type = this.getAddEventListenerTypeByRequestPayloadType(payload.type);
2660
+ const listener = await window.fdc3.addEventListener(type, handler);
2661
+ this.listenersCollection[listenerUUID] = listener;
2662
+ return { listenerUUID };
2663
+ }
2664
+ getAddEventListenerTypeByRequestPayloadType(requestType) {
2665
+ if (!requestType) {
2666
+ return null;
2667
+ }
2668
+ return ChannelEventToTypeDictionary[requestType] ?? null;
2669
+ }
2670
+ async handleBroadcastRequest({ payload }) {
2671
+ const { channelId, context } = payload;
2672
+ const channel = await this.getChannelById(channelId);
2673
+ await (channel ?? window.fdc3)?.broadcast(context);
2674
+ return {};
2675
+ }
2676
+ async handleUnsubscribeRequest({ payload }) {
2677
+ const listener = this.listenersCollection[payload.listenerUUID];
2678
+ if (!listener) {
2679
+ return { error: "MalformedMessage", reason: `Cannot find listener with listenerUUID: ${payload.listenerUUID}` };
2680
+ }
2681
+ this.logger?.info(`Unsubscribing listener with UUID: ${payload.listenerUUID}`);
2682
+ await listener.unsubscribe();
2683
+ delete this.listenersCollection[payload.listenerUUID];
2684
+ return {};
2685
+ }
2686
+ async handleCreatePrivateChannelRequest() {
2687
+ const privateChannel = await window.fdc3?.createPrivateChannel();
2688
+ if (!privateChannel) {
2689
+ return { error: "CreationFailed" };
2690
+ }
2691
+ this.privateChannelsCollection[privateChannel.id] = privateChannel;
2692
+ const pureChannel = JSON.parse(JSON.stringify(privateChannel));
2693
+ return { privateChannel: pureChannel };
2694
+ }
2695
+ async handleGetCurrentChannelRequest() {
2696
+ const channel = await window.fdc3?.getCurrentChannel();
2697
+ const pureChannel = JSON.parse(JSON.stringify(channel));
2698
+ return { channel: pureChannel };
2699
+ }
2700
+ async handleGetCurrentContextRequest({ payload }) {
2701
+ const channel = await window.fdc3?.getOrCreateChannel(payload.channelId);
2702
+ const contextType = payload.contextType ?? undefined;
2703
+ const context = await channel?.getCurrentContext(contextType);
2704
+ return { context };
2705
+ }
2706
+ async handleGetOrCreateChannelRequest({ payload }) {
2707
+ const isPrivateChannel = this.privateChannelsCollection[payload.channelId] ?? payload.channelId.startsWith(privateChannelPrefix);
2708
+ if (isPrivateChannel) {
2709
+ return { error: "AccessDenied" };
2710
+ }
2711
+ const channel = await window.fdc3?.getOrCreateChannel(payload.channelId);
2712
+ const pureChannel = JSON.parse(JSON.stringify(channel));
2713
+ return { channel: pureChannel };
2714
+ }
2715
+ async handleGetUserChannelsRequest() {
2716
+ const userChannels = await window.fdc3?.getUserChannels() ?? [];
2717
+ const pureChannels = userChannels.map((ch) => JSON.parse(JSON.stringify(ch)));
2718
+ return { userChannels: pureChannels };
2719
+ }
2720
+ async handleJoinUserChannelRequest({ payload }) {
2721
+ await window.fdc3?.joinUserChannel(payload.channelId);
2722
+ return {};
2723
+ }
2724
+ async handleLeaveCurrentChannel(request) {
2725
+ await window.fdc3?.leaveCurrentChannel();
2726
+ return {};
2727
+ }
2728
+ async handlePrivateChannelAddEventListenerRequest({ payload }) {
2729
+ const { listenerType, privateChannelId } = payload;
2730
+ this.logger?.info(`Received private channel addEventListenerRequest with payload: ${JSON.stringify(payload)}`);
2731
+ const privateChannel = this.privateChannelsCollection[privateChannelId];
2732
+ if (!privateChannel) {
2733
+ return { error: "NoChannelFound" };
2734
+ }
2735
+ const handler = (event) => {
2736
+ this.logger?.info(`Received event: ${JSON.stringify(event)}`);
2737
+ if (listenerType && listenerType !== event.type) {
2738
+ this.logger?.info(`Listener type from private channel addEventListenerRequest '${listenerType}' does not match the event type '${event.type}'. Handler won't be invoked...`);
2739
+ return;
2740
+ }
2741
+ const eventUuid = nanoid();
2742
+ const responseType = {
2743
+ type: this.getPrivateChannelResponseType(event.type),
2744
+ meta: {
2745
+ eventUuid,
2746
+ timestamp: new Date()
2747
+ },
2748
+ payload: {
2749
+ contextType: event.details?.contextType,
2750
+ privateChannelId: payload.privateChannelId
2751
+ }
2752
+ };
2753
+ this.logger?.info(`Sending private channel event response: ${JSON.stringify(responseType)}`);
2754
+ this.sendBridgeMessage(responseType);
2755
+ };
2756
+ const listenerUUID = nanoid();
2757
+ const listener = await privateChannel.addEventListener(payload.listenerType ?? null, handler);
2758
+ this.listenersCollection[listenerUUID] = listener;
2759
+ return { listenerUUID };
2760
+ }
2761
+ async handlePrivateChannelDisconnectRequest({ payload }) {
2762
+ const privateChannel = this.privateChannelsCollection[payload.channelId];
2763
+ if (!privateChannel) {
2764
+ return { error: "NoChannelFound" };
2765
+ }
2766
+ await privateChannel.disconnect();
2767
+ delete this.privateChannelsCollection[payload.channelId];
2768
+ return {};
2769
+ }
2770
+ async handlePrivateChannelUnsubscribeEventListenerRequest({ payload }) {
2771
+ const listener = this.listenersCollection[payload.listenerUUID];
2772
+ if (!listener) {
2773
+ return { error: "MalformedMessage", reason: `Cannot find listener with id ${payload.listenerUUID}` };
2774
+ }
2775
+ await listener.unsubscribe();
2776
+ delete this.listenersCollection[payload.listenerUUID];
2777
+ return {};
2778
+ }
2779
+ decorateResponse({ request, payload, responseUuid }) {
2780
+ return {
2781
+ type: this.operations[request.type].responseType,
2782
+ meta: {
2783
+ requestUuid: request.meta.requestUuid,
2784
+ responseUuid: responseUuid,
2785
+ source: request.meta.source,
2786
+ timestamp: new Date()
2787
+ },
2788
+ payload
2789
+ };
2790
+ }
2791
+ getPrivateChannelResponseType(eventType) {
2792
+ if (eventType === "addContextListener") {
2793
+ return "privateChannelOnAddContextListenerEvent";
2794
+ }
2795
+ if (eventType === "disconnect") {
2796
+ return "privateChannelOnDisconnectEvent";
2797
+ }
2798
+ if (eventType === "unsubscribe") {
2799
+ return "privateChannelOnUnsubscribeEvent";
2800
+ }
2801
+ throw new Error(`Invalid event type: ${eventType}`);
2802
+ }
2803
+ }
2804
+
2805
+ class BridgeController {
2806
+ ioController;
2807
+ ioc;
2808
+ _messageChannel;
2809
+ _connectionCompleted = false;
2810
+ _helloMessageOrigin;
2811
+ logger;
2812
+ _globalMessageHandler;
2813
+ constructor(ioController, ioc) {
2814
+ this.ioController = ioController;
2815
+ this.ioc = ioc;
2816
+ }
2817
+ configure() {
2818
+ this._globalMessageHandler = this.globalMessageHandler.bind(this);
2819
+ window.addEventListener("message", this._globalMessageHandler);
2820
+ }
2821
+ sendMessage(data) {
2822
+ this._messageChannel?.port1.postMessage(data);
2823
+ }
2824
+ globalMessageHandler(event) {
2825
+ const parentURL = document.referrer;
2826
+ const origin = new URL(parentURL).origin;
2827
+ if (event.origin !== origin) {
2828
+ return;
2829
+ }
2830
+ if (event.data?.type === WCPMessageTypes.WCP1Hello) {
2831
+ return this.handleHelloConnectionRequest(event.source, event.origin, event.data);
2832
+ }
2833
+ }
2834
+ handleHelloConnectionRequest(source, origin, data) {
2835
+ if (this._messageChannel) {
2836
+ console.warn(`${WCPMessageTypes.WCP1Hello} already heard. Message channel port created`);
2837
+ return;
2838
+ }
2839
+ const decodedRequest = wcp1HelloDecoder.run(data);
2840
+ if (!decodedRequest.ok) {
2841
+ const errorMsg = `Received invalid '${WCPMessageTypes.WCP1Hello}' request: ${JSON.stringify(data)}. Reason: ${decodedRequest.error.message} at ${decodedRequest.error.at}`;
2842
+ console.error(errorMsg);
2843
+ source.postMessage({ error: "MalformedMessage", message: errorMsg }, origin);
2844
+ return;
2845
+ }
2846
+ this._helloMessageOrigin = origin;
2847
+ this._messageChannel = this.ioc.createMessageChannel();
2848
+ this._messageChannel.port1.onmessage = this.handlePortMessage.bind(this);
2849
+ this.sendHandshake(source, origin, data);
2850
+ window.removeEventListener("message", this._globalMessageHandler);
2851
+ }
2852
+ async handlePortMessage(event) {
2853
+ this.logger?.info(`Received port message with data: ${JSON.stringify(event.data)}}`);
2854
+ if (!this._connectionCompleted && event.data?.type !== WCPMessageTypes.WCP6Goodbye && event.data.type !== WCPMessageTypes.WCP4ValidateAppIdentity) {
2855
+ console.warn("Web Connection Protocol not completed yet. Ignoring message");
2856
+ return;
2857
+ }
2858
+ if (event.data?.type === WCPMessageTypes.WCP4ValidateAppIdentity) {
2859
+ return this.handleAppIdentityValidationRequest(event.data);
2860
+ }
2861
+ if (event.data?.type === WCPMessageTypes.WCP6Goodbye) {
2862
+ return this.handleGoodbyeRequest(event.data);
2863
+ }
2864
+ const result = await this.ioc.domainsController.handleMessage(event.data);
2865
+ this.logger?.info(`Sending response message: ${JSON.stringify(result)}`);
2866
+ this.sendMessage(result);
2867
+ }
2868
+ async handleAppIdentityValidationRequest(data) {
2869
+ const decodedRequest = wcp4ValidateAppIdentityDecoder.run(data);
2870
+ if (!decodedRequest.ok) {
2871
+ const errorMsg = `Received invalid '${WCPMessageTypes.WCP4ValidateAppIdentity}' request: ${JSON.stringify(data)}. Reason: ${decodedRequest.error.message} at ${decodedRequest.error.at}`;
2872
+ console.error(errorMsg);
2873
+ this.sendMessage({ error: "MalformedMessage", message: errorMsg });
2874
+ return;
2875
+ }
2876
+ const { actualUrl, identityUrl } = data.payload;
2877
+ await this.ioController.initializeLibs();
2878
+ this.logger = this.ioController.io?.logger.subLogger("bridge.controller");
2879
+ this.logger?.info(`IOBrowser and FDC3 libs are initialized. Received ${data.type} request: ${JSON.stringify(data)}`);
2880
+ const validationResult = this.ioController.validateIdentity({ actualUrl, identityUrl, helloMsgOrigin: this._helloMessageOrigin });
2881
+ if (!validationResult.isValid) {
2882
+ this.logger?.info(`App validation failure. Reason: ${validationResult.message}`);
2883
+ this.sendValidationFailure(data.meta.connectionAttemptUuid, validationResult.message);
2884
+ this.cleanSetup();
2885
+ return;
2886
+ }
2887
+ await this.sendValidationSuccess(data.meta.connectionAttemptUuid, validationResult.appId);
2888
+ this.logger?.info(`App validation is successful. Connection is completed`);
2889
+ this._connectionCompleted = true;
2890
+ }
2891
+ sendHandshake(source, origin, data) {
2892
+ const handshakeMsg = {
2893
+ type: WCPMessageTypes.WCP3Handshake,
2894
+ meta: {
2895
+ connectionAttemptUuid: data.meta.connectionAttemptUuid,
2896
+ timestamp: new Date()
2897
+ },
2898
+ payload: {
2899
+ channelSelectorUrl: true,
2900
+ intentResolverUrl: true,
2901
+ fdc3Version: window.fdc3Info.standardVersion,
2902
+ }
2903
+ };
2904
+ const transfer = this._messageChannel ? [this._messageChannel.port2] : undefined;
2905
+ source.postMessage(handshakeMsg, origin, transfer);
2906
+ }
2907
+ sendValidationFailure(attempt, errorMsg) {
2908
+ const validationFailureMsg = {
2909
+ type: "WCP5ValidateAppIdentityFailedResponse",
2910
+ meta: {
2911
+ connectionAttemptUuid: attempt,
2912
+ timestamp: new Date()
2913
+ },
2914
+ payload: {
2915
+ message: errorMsg
2916
+ }
2917
+ };
2918
+ console.warn(`App Identity Validation failed. Reason: ${errorMsg}`);
2919
+ this.sendMessage(validationFailureMsg);
2920
+ }
2921
+ async sendValidationSuccess(attempt, appId) {
2922
+ const implementationMetadata = await window.fdc3?.getInfo();
2923
+ const instanceId = this.ioController.io?.interop.instance.instance;
2924
+ const interopInstance = this.ioController.io?.interop.instance;
2925
+ const instanceUuid = interopInstance.uuid;
2926
+ const validationSuccessMsg = {
2927
+ type: "WCP5ValidateAppIdentityResponse",
2928
+ meta: {
2929
+ connectionAttemptUuid: attempt,
2930
+ timestamp: new Date()
2931
+ },
2932
+ payload: {
2933
+ appId,
2934
+ instanceId,
2935
+ instanceUuid,
2936
+ implementationMetadata
2937
+ }
2938
+ };
2939
+ this.sendMessage(validationSuccessMsg);
2940
+ }
2941
+ cleanSetup() {
2942
+ this._helloMessageOrigin = undefined;
2943
+ this._messageChannel?.port1.close();
2944
+ this._messageChannel?.port2.close();
2945
+ this._connectionCompleted = false;
2946
+ this._messageChannel = undefined;
2947
+ if (window.__karma__) {
2948
+ this.configure();
2949
+ this.ioController._initializationStarted = false;
2950
+ }
2951
+ }
2952
+ handleGoodbyeRequest(data) {
2953
+ const decodedRequest = wcp6GoodbyeRequestDecoder.run(data);
2954
+ if (!decodedRequest.ok) {
2955
+ const errorMsg = `Received invalid '${WCPMessageTypes.WCP6Goodbye}' request: ${JSON.stringify(data)}. Reason: ${decodedRequest.error.message} at ${decodedRequest.error.at}`;
2956
+ console.error(errorMsg);
2957
+ this.sendMessage({ error: "MalformedMessage", message: errorMsg });
2958
+ return;
2959
+ }
2960
+ this.cleanSetup();
2961
+ }
2962
+ }
2963
+
2964
+ class DomainsController {
2965
+ channelsController;
2966
+ intentsController;
2967
+ applicationsController;
2968
+ ioController;
2969
+ domains;
2970
+ logger;
2971
+ constructor(channelsController, intentsController, applicationsController, ioController) {
2972
+ this.channelsController = channelsController;
2973
+ this.intentsController = intentsController;
2974
+ this.applicationsController = applicationsController;
2975
+ this.ioController = ioController;
2976
+ this.setupDomains();
2977
+ this.logger = this.ioController.getLogger("domains.controller");
2978
+ }
2979
+ async handleMessage(data) {
2980
+ const decodedDataTypeRequest = requestMessageTypeDecoder.run(data.type);
2981
+ if (!decodedDataTypeRequest.ok) {
2982
+ this.logger?.error(`Received invalid request type: ${JSON.stringify(data)}`);
2983
+ return { error: "MalformedMessage", message: `Received invalid request message type: ${decodedDataTypeRequest.error.message}` };
2984
+ }
2985
+ const domain = Object.values(this.domains).find((domain) => domain.requestTypes.includes(data.type));
2986
+ if (!domain) {
2987
+ this.logger?.error(`Cannot find domain for message type: ${data.type}`);
2988
+ return { error: "MalformedMessage", message: `Received unsupported message type: ${data.type}` };
2989
+ }
2990
+ this.logger?.info(`Sending request ${data.type} to domain '${domain.name}'`);
2991
+ const result = await domain.controller.handleControl(data);
2992
+ const decodedResultTypeResponse = responseMessageTypeDecoder.run(result.type);
2993
+ if (!decodedResultTypeResponse.ok) {
2994
+ this.logger?.error(`Received invalid response type: ${JSON.stringify(data)}`);
2995
+ return { error: "MalformedMessage", message: `Received invalid response message type: ${decodedResultTypeResponse.error.message}` };
2996
+ }
2997
+ this.logger?.info(`Returning domain result: ${JSON.stringify(result)}`);
2998
+ return result;
2999
+ }
3000
+ setupDomains() {
3001
+ const channelsRequestTypes = ["addContextListenerRequest", "addEventListenerRequest", "broadcastRequest", "contextListenerUnsubscribeRequest", "createPrivateChannelRequest", "eventListenerUnsubscribeRequest", "getCurrentChannelRequest", "getCurrentContextRequest", "getOrCreateChannelRequest", "getUserChannelsRequest", "joinUserChannelRequest", "leaveCurrentChannelRequest", "privateChannelAddEventListenerRequest", "privateChannelDisconnectRequest", "privateChannelUnsubscribeEventListenerRequest"];
3002
+ const intentsRequestTypes = ["addIntentListenerRequest", "findIntentRequest", "findIntentsByContextRequest", "intentListenerUnsubscribeRequest", "intentResultRequest", "raiseIntentForContextRequest", "raiseIntentRequest"];
3003
+ const applicationsRequestTypes = ["findInstancesRequest", "getAppMetadataRequest", "getInfoRequest", "openRequest", "heartbeatAcknowledgementRequest"];
3004
+ this.domains = {
3005
+ channels: {
3006
+ name: "channels",
3007
+ controller: this.channelsController,
3008
+ requestTypes: channelsRequestTypes
3009
+ },
3010
+ intents: {
3011
+ name: "intents",
3012
+ controller: this.intentsController,
3013
+ requestTypes: intentsRequestTypes
3014
+ },
3015
+ applications: {
3016
+ name: "applications",
3017
+ controller: this.applicationsController,
3018
+ requestTypes: applicationsRequestTypes
3019
+ }
3020
+ };
3021
+ }
3022
+ }
3023
+
3024
+ const rejectWithErrorObj = (reject, error) => {
3025
+ if (error instanceof Error) {
3026
+ reject(error.message);
3027
+ return;
3028
+ }
3029
+ if (typeof error === "string") {
3030
+ reject(new Error(error));
3031
+ return;
3032
+ }
3033
+ reject(new Error(JSON.stringify(error)));
3034
+ };
3035
+ const wrapPromise = () => {
3036
+ let wrapperResolve;
3037
+ let wrapperReject;
3038
+ const promise = new Promise((resolve, reject) => {
3039
+ wrapperResolve = resolve;
3040
+ wrapperReject = reject;
3041
+ });
3042
+ return { promise, resolve: wrapperResolve, reject: wrapperReject };
3043
+ };
3044
+ const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => {
3045
+ return new Promise((resolve, reject) => {
3046
+ const timeout = setTimeout(() => {
3047
+ const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`;
3048
+ reject(new Error(message));
3049
+ }, timeoutMilliseconds);
3050
+ promise()
3051
+ .then((result) => {
3052
+ clearTimeout(timeout);
3053
+ resolve(result);
3054
+ })
3055
+ .catch((error) => {
3056
+ clearTimeout(timeout);
3057
+ rejectWithErrorObj(reject, error);
3058
+ });
3059
+ });
3060
+ };
3061
+ const compareOrigins = (url1, url2) => {
3062
+ try {
3063
+ const parsedUrl1 = new URL(url1);
3064
+ const parsedUrl2 = new URL(url2);
3065
+ return parsedUrl1.origin === parsedUrl2.origin;
3066
+ }
3067
+ catch (e) {
3068
+ return false;
3069
+ }
3070
+ };
3071
+ const removeTrailingSlash = (pathname) => {
3072
+ return pathname.endsWith("/")
3073
+ ? pathname.slice(0, -1)
3074
+ : pathname;
3075
+ };
3076
+ const isRecordUrlMatchToIdentityUrl = (recordUrl, identityUrl) => {
3077
+ let parsedRecordUrl;
3078
+ let parsedIdentityUrl;
3079
+ try {
3080
+ parsedRecordUrl = new URL(recordUrl);
3081
+ parsedIdentityUrl = new URL(identityUrl);
3082
+ }
3083
+ catch (error) {
3084
+ return false;
3085
+ }
3086
+ if (parsedRecordUrl.origin !== parsedIdentityUrl.origin) {
3087
+ return false;
3088
+ }
3089
+ const recordPath = removeTrailingSlash(parsedRecordUrl.pathname);
3090
+ const identityPath = removeTrailingSlash(parsedIdentityUrl.pathname);
3091
+ if (recordPath !== identityPath) {
3092
+ return false;
3093
+ }
3094
+ for (const [key, value] of parsedRecordUrl.searchParams) {
3095
+ if (parsedIdentityUrl.searchParams.get(key) !== value) {
3096
+ return false;
3097
+ }
3098
+ }
3099
+ if (parsedRecordUrl.hash && parsedRecordUrl.hash !== parsedIdentityUrl.hash) {
3100
+ return false;
3101
+ }
3102
+ return true;
3103
+ };
3104
+ const checkIfFDC3Channel = (object) => {
3105
+ if (!object || typeof object !== "object" || Array.isArray(object)) {
3106
+ return false;
3107
+ }
3108
+ if (!channelTypes.includes(object?.type)) {
3109
+ return false;
3110
+ }
3111
+ return defaultChannelsProps.every((prop) => Object.keys(object).includes(prop));
3112
+ };
3113
+ const checkIfFDC3Context = (object) => {
3114
+ if (!object || typeof object !== "object" || Array.isArray(object)) {
3115
+ return false;
3116
+ }
3117
+ return "type" in object && typeof object.type === "string";
3118
+ };
3119
+
3120
+ class IOController {
3121
+ _io;
3122
+ _initializationStarted = false;
3123
+ logger;
3124
+ get io() {
3125
+ return this._io;
3126
+ }
3127
+ validateIdentity({ actualUrl, identityUrl, helloMsgOrigin }) {
3128
+ if (!helloMsgOrigin) {
3129
+ return { isValid: false, message: "There's no WCP1Hello message origin provided" };
3130
+ }
3131
+ this.logger?.info(`Comparing origins of identityUrl '${identityUrl}' with actualUrl '${actualUrl}'`);
3132
+ const sameOriginWithActualUrl = compareOrigins(identityUrl, actualUrl);
3133
+ if (!sameOriginWithActualUrl) {
3134
+ return { isValid: false, message: `Origins of actualUrl (${actualUrl}) and identityUrl (${identityUrl}) does not match` };
3135
+ }
3136
+ this.logger?.info(`Comparing origins of identityUrl '${identityUrl}' with helloMsgOrigin '${helloMsgOrigin}'`);
3137
+ const sameOriginWithHelloEvent = compareOrigins(identityUrl, helloMsgOrigin);
3138
+ if (!sameOriginWithHelloEvent) {
3139
+ return { isValid: false, message: `Origins of initial WCP1Hello event (${helloMsgOrigin}) and identityUrl (${identityUrl}) does not match` };
3140
+ }
3141
+ this.logger?.info(`Searching in app directory for definition matching the provided identity url (${identityUrl})`);
3142
+ const application = this.io?.appManager.applications().find((app) => isRecordUrlMatchToIdentityUrl(app.userProperties.details.url, identityUrl));
3143
+ return application
3144
+ ? { isValid: true, appId: application.name }
3145
+ : { isValid: false, message: `There's no app definition matching the provided identityUrl: ${identityUrl}` };
3146
+ }
3147
+ async initializeLibs() {
3148
+ if (this._initializationStarted) {
3149
+ return;
3150
+ }
3151
+ const fdc3ReadyPromise = this.createFdc3ReadyPromise();
3152
+ this._initializationStarted = true;
3153
+ await this.initializeBrowser();
3154
+ await fdc3ReadyPromise;
3155
+ }
3156
+ getLogger(name) {
3157
+ if (!this._io) {
3158
+ return;
3159
+ }
3160
+ return this._io.logger.subLogger(`fdc3-web-bridge.${name}`);
3161
+ }
3162
+ createFdc3ReadyPromise() {
3163
+ return promisePlus(() => {
3164
+ return new Promise((resolve) => {
3165
+ const fdc3ReadyHandler = () => {
3166
+ window.removeEventListener("fdc3Ready", fdc3ReadyHandler);
3167
+ resolve();
3168
+ };
3169
+ window.addEventListener("fdc3Ready", fdc3ReadyHandler);
3170
+ });
3171
+ }, FDC3_READY_TIMEOUT, `Timeout of ${FDC3_READY_TIMEOUT}ms waiting for @interopio/fdc3 lib to initialize`);
3172
+ }
3173
+ async initializeBrowser() {
3174
+ const parentWindowId = this.getParentWindowId();
3175
+ const config = {
3176
+ identity: {
3177
+ instance: parentWindowId,
3178
+ uuid: parentWindowId,
3179
+ }
3180
+ };
3181
+ this._io = await window.IOBrowser(config);
3182
+ window.io = this._io;
3183
+ this.initLogger();
3184
+ }
3185
+ getParentWindowId() {
3186
+ const urlParams = new URLSearchParams(window.location.search);
3187
+ const name = urlParams.get('parentId');
3188
+ return name ?? "";
3189
+ }
3190
+ initLogger() {
3191
+ this.logger = this.io?.logger.subLogger("io.controller");
3192
+ }
3193
+ }
3194
+
3195
+ const { nonEmptyStringDecoder } = decoders.common;
3196
+ const addIntentListenerRequestPayloadDecoder = object$1({
3197
+ intent: nonEmptyStringDecoder
3198
+ });
3199
+ const addIntentListenerRequestDecoder = object$1({
3200
+ type: constant$1("addIntentListenerRequest"),
3201
+ meta: addContextListenerRequestMetaDecoder,
3202
+ payload: addIntentListenerRequestPayloadDecoder
3203
+ });
3204
+ const findIntentRequestPayloadDecoder = object$1({
3205
+ intent: nonEmptyStringDecoder,
3206
+ context: optional$1(contextDecoder),
3207
+ resultType: optional$1(nonEmptyStringDecoder)
3208
+ });
3209
+ const findIntentRequestDecoder = object$1({
3210
+ type: constant$1("findIntentRequest"),
3211
+ meta: addContextListenerRequestMetaDecoder,
3212
+ payload: findIntentRequestPayloadDecoder
3213
+ });
3214
+ const findIntentsByContextRequestPayloadDecoder = object$1({
3215
+ context: contextDecoder,
3216
+ resultType: optional$1(nonEmptyStringDecoder)
3217
+ });
3218
+ const findIntentsByContextRequestDecoder = object$1({
3219
+ type: constant$1("findIntentsByContextRequest"),
3220
+ meta: addContextListenerRequestMetaDecoder,
3221
+ payload: findIntentsByContextRequestPayloadDecoder
3222
+ });
3223
+ const intentListenerUnsubscribeRequestPayloadDecoder = object$1({
3224
+ listenerUUID: nonEmptyStringDecoder
3225
+ });
3226
+ const intentListenerUnsubscribeRequestDecoder = object$1({
3227
+ type: constant$1("intentListenerUnsubscribeRequest"),
3228
+ meta: addContextListenerRequestMetaDecoder,
3229
+ payload: intentListenerUnsubscribeRequestPayloadDecoder
3230
+ });
3231
+ const intentResultDecoder = object$1({
3232
+ context: optional$1(contextDecoder),
3233
+ channel: optional$1(channelDecoder)
3234
+ });
3235
+ const intentResultRequestPayloadDecoder = object$1({
3236
+ intentEventUuid: nonEmptyStringDecoder,
3237
+ intentResult: intentResultDecoder,
3238
+ raiseIntentRequestUuid: nonEmptyStringDecoder
3239
+ });
3240
+ const intentResultRequestDecoder = object$1({
3241
+ type: constant$1("intentResultRequest"),
3242
+ meta: addContextListenerRequestMetaDecoder,
3243
+ payload: intentResultRequestPayloadDecoder
3244
+ });
3245
+ const raiseIntentForContextRequestPayloadDecoder = object$1({
3246
+ context: contextDecoder,
3247
+ app: optional$1(appIdentifierDecoder)
3248
+ });
3249
+ const raiseIntentForContextRequestDecoder = object$1({
3250
+ type: constant$1("raiseIntentForContextRequest"),
3251
+ meta: addContextListenerRequestMetaDecoder,
3252
+ payload: raiseIntentForContextRequestPayloadDecoder
3253
+ });
3254
+ const raiseIntentRequestPayloadDecoder = object$1({
3255
+ intent: nonEmptyStringDecoder,
3256
+ context: contextDecoder,
3257
+ app: optional$1(appIdentifierDecoder)
3258
+ });
3259
+ const raiseIntentRequestDecoder = object$1({
3260
+ type: constant$1("raiseIntentRequest"),
3261
+ meta: addContextListenerRequestMetaDecoder,
3262
+ payload: raiseIntentRequestPayloadDecoder
3263
+ });
3264
+ const raiseIntentResultRequestDecoder = object$1({
3265
+ type: constant$1("raiseIntentResultRequest"),
3266
+ meta: addContextListenerRequestMetaDecoder,
3267
+ payload: oneOf$1(raiseIntentRequestPayloadDecoder, raiseIntentForContextRequestPayloadDecoder)
3268
+ });
3269
+ const addIntentListenerResponsePayloadDecoder = object$1({
3270
+ error: optional$1(fluffyErrorDecoder),
3271
+ listenerUUID: optional$1(nonEmptyStringDecoder)
3272
+ });
3273
+ const addIntentListenerResponseDecoder = object$1({
3274
+ type: constant$1("addIntentListenerResponse"),
3275
+ meta: addContextListenerResponseMetaDecoder,
3276
+ payload: addIntentListenerResponsePayloadDecoder
3277
+ });
3278
+ const intentMetadataDecoder = object$1({
3279
+ name: nonEmptyStringDecoder,
3280
+ displayName: optional$1(string$1())
3281
+ });
3282
+ const appIntentDecoder = object$1({
3283
+ apps: array$1(appMetadataDecoder),
3284
+ intent: intentMetadataDecoder
3285
+ });
3286
+ const findIntentResponsePayloadDecoder = object$1({
3287
+ error: optional$1(findInstancesErrorsDecoder),
3288
+ appIntent: optional$1(appIntentDecoder)
3289
+ });
3290
+ const findIntentResponseDecoder = object$1({
3291
+ type: constant$1("findIntentResponse"),
3292
+ meta: addContextListenerResponseMetaDecoder,
3293
+ payload: findIntentResponsePayloadDecoder
3294
+ });
3295
+ const findIntentsByContextResponsePayloadDecoder = object$1({
3296
+ error: optional$1(findInstancesErrorsDecoder),
3297
+ appIntents: optional$1(array$1(appIntentDecoder))
3298
+ });
3299
+ const findIntentsByContextResponseDecoder = object$1({
3300
+ type: constant$1("findIntentsByContextResponse"),
3301
+ meta: addContextListenerResponseMetaDecoder,
3302
+ payload: findIntentsByContextResponsePayloadDecoder
3303
+ });
3304
+ const intentListenerUnsubscribeResponseDecoder = object$1({
3305
+ type: constant$1("intentListenerUnsubscribeResponse"),
3306
+ meta: addContextListenerResponseMetaDecoder,
3307
+ payload: broadcastResponsePayloadDecoder
3308
+ });
3309
+ const intentResultResponseDecoder = object$1({
3310
+ type: constant$1("intentResultResponse"),
3311
+ meta: addContextListenerResponseMetaDecoder,
3312
+ payload: broadcastResponsePayloadDecoder
3313
+ });
3314
+ const intentResolutionDecoder = object$1({
3315
+ intent: nonEmptyStringDecoder,
3316
+ source: appIdentifierDecoder
3317
+ });
3318
+ const raiseIntentForContextResponsePayloadDecoder = object$1({
3319
+ error: optional$1(findInstancesErrorsDecoder),
3320
+ intentResolution: optional$1(intentResolutionDecoder),
3321
+ appIntents: optional$1(array$1(appIntentDecoder))
3322
+ });
3323
+ const raiseIntentForContextResponseDecoder = object$1({
3324
+ type: constant$1("raiseIntentForContextResponse"),
3325
+ meta: addContextListenerResponseMetaDecoder,
3326
+ payload: raiseIntentForContextResponsePayloadDecoder
3327
+ });
3328
+ const raiseIntentResponsePayloadDecoder = object$1({
3329
+ error: optional$1(findInstancesErrorsDecoder),
3330
+ intentResolution: optional$1(intentResolutionDecoder),
3331
+ appIntent: optional$1(appIntentDecoder)
3332
+ });
3333
+ const raiseIntentResponseDecoder = object$1({
3334
+ type: constant$1("raiseIntentResponse"),
3335
+ meta: addContextListenerResponseMetaDecoder,
3336
+ payload: raiseIntentResponsePayloadDecoder
3337
+ });
3338
+ const raiseIntentResultResponsePayloadDecoder = object$1({
3339
+ error: optional$1(responsePayloadErrorDecoder),
3340
+ intentResult: optional$1(intentResultDecoder),
3341
+ });
3342
+ const raiseIntentResultResponseDecoder = object$1({
3343
+ type: constant$1("raiseIntentResultResponse"),
3344
+ meta: addContextListenerResponseMetaDecoder,
3345
+ payload: raiseIntentResultResponsePayloadDecoder
3346
+ });
3347
+
3348
+ class IntentsController {
3349
+ sendBridgeMessage;
3350
+ addPrivateChannel;
3351
+ logger;
3352
+ listenersCollection = {};
3353
+ intentResolutionsCollection = {};
3354
+ intentEventPayloadCollection = {};
3355
+ intentHandlerResultPromiseCollection = {};
3356
+ operations = {
3357
+ addIntentListenerRequest: { requestType: "addIntentListenerRequest", requestDecoder: addIntentListenerRequestDecoder, responseType: "addIntentListenerResponse", responseDecoder: addIntentListenerResponseDecoder, execute: this.handleAddIntentListenerRequest.bind(this) },
3358
+ findIntentRequest: { requestType: "findIntentRequest", requestDecoder: findIntentRequestDecoder, responseType: "findIntentResponse", responseDecoder: findIntentResponseDecoder, execute: this.handleFindIntentRequest.bind(this) },
3359
+ findIntentsByContextRequest: { requestType: "findIntentsByContextRequest", requestDecoder: findIntentsByContextRequestDecoder, responseType: "findIntentsByContextResponse", responseDecoder: findIntentsByContextResponseDecoder, execute: this.handleFindIntentsByContextRequest.bind(this) },
3360
+ intentListenerUnsubscribeRequest: { requestType: "intentListenerUnsubscribeRequest", requestDecoder: intentListenerUnsubscribeRequestDecoder, responseType: "intentListenerUnsubscribeResponse", responseDecoder: intentListenerUnsubscribeResponseDecoder, execute: this.handleIntentListenerUnsubscribeRequest.bind(this) },
3361
+ intentResultRequest: { requestType: "intentResultRequest", requestDecoder: intentResultRequestDecoder, responseType: "intentResultResponse", responseDecoder: intentResultResponseDecoder, execute: this.handleIntentResultRequest.bind(this) },
3362
+ raiseIntentForContextRequest: { requestType: "raiseIntentForContextRequest", requestDecoder: raiseIntentForContextRequestDecoder, responseType: "raiseIntentForContextResponse", responseDecoder: raiseIntentForContextResponseDecoder, execute: this.handleRaiseIntentForContextRequest.bind(this) },
3363
+ raiseIntentRequest: { requestType: "raiseIntentRequest", requestDecoder: raiseIntentRequestDecoder, responseType: "raiseIntentResponse", responseDecoder: raiseIntentResponseDecoder, execute: this.handleRaiseIntentRequest.bind(this) },
3364
+ raiseIntentResultRequest: { requestType: "raiseIntentResultRequest", requestDecoder: raiseIntentResultRequestDecoder, responseType: "raiseIntentResultResponse", responseDecoder: raiseIntentResultResponseDecoder, execute: this.handleRaiseIntentResultResponse.bind(this) },
3365
+ };
3366
+ constructor(sendBridgeMessage, addPrivateChannel, logger) {
3367
+ this.sendBridgeMessage = sendBridgeMessage;
3368
+ this.addPrivateChannel = addPrivateChannel;
3369
+ this.logger = logger;
3370
+ }
3371
+ async handleControl(request) {
3372
+ const operation = this.operations[request.type];
3373
+ const responseUuid = nanoid(10);
3374
+ if (!operation) {
3375
+ this.logger?.error(`Controller cannot perform unsupported message: ${JSON.stringify(request)}`);
3376
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received unsupported message type: ${request.type} for request: ${JSON.stringify(request)}` } });
3377
+ }
3378
+ this.logger?.info(`Received request: ${JSON.stringify(request)}`);
3379
+ const { requestDecoder, responseDecoder, execute } = operation;
3380
+ const decodedRequest = requestDecoder.run(request);
3381
+ if (!decodedRequest.ok) {
3382
+ this.logger?.error(`Received invalid request: ${JSON.stringify(request)}`);
3383
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received invalid request message. Reason: ${decodedRequest.error.message}` } });
3384
+ }
3385
+ this.logger?.info(`Handling ${request.type} request: ${JSON.stringify(request)}`);
3386
+ let payload;
3387
+ try {
3388
+ payload = await execute(request);
3389
+ }
3390
+ catch (error) {
3391
+ payload = { error: typeof error === "string" ? error : error.message };
3392
+ }
3393
+ this.logger?.info(`Execution logic for ${request.type} completed. Received payload: ${JSON.stringify(payload)}`);
3394
+ const response = this.decorateResponse({ request, payload, responseUuid });
3395
+ const decodedResponse = responseDecoder.run(response);
3396
+ if (!decodedResponse.ok) {
3397
+ this.logger?.error(`Invalid response type ${response.type}. Error: ${JSON.stringify(decodedResponse.error)}`);
3398
+ return this.decorateResponse({ request, responseUuid, payload: { error: "MalformedMessage", message: `Received invalid response message. Reason: ${decodedResponse.error}` } });
3399
+ }
3400
+ this.logger?.info(`Returning response: ${JSON.stringify(response)}`);
3401
+ return response;
3402
+ }
3403
+ async handleAddIntentListenerRequest({ meta, payload }) {
3404
+ const handler = async (context, metadata) => {
3405
+ const eventUuid = nanoid();
3406
+ this.logger?.info(`Received intent event with context: ${JSON.stringify(context)} and metadata: ${JSON.stringify(metadata)}`);
3407
+ const intentEventPayload = {
3408
+ intent: payload.intent,
3409
+ context,
3410
+ originatingApp: {
3411
+ appId: metadata?.source.appId ?? "",
3412
+ instanceId: metadata?.source.instanceId,
3413
+ desktopAgent: DESKTOP_AGENT_NAME
3414
+ },
3415
+ raiseIntentRequestUuid: meta.requestUuid
3416
+ };
3417
+ this.intentEventPayloadCollection[meta.requestUuid] = intentEventPayload;
3418
+ const intentEventMsg = {
3419
+ type: "intentEvent",
3420
+ meta: { eventUuid, timestamp: new Date() },
3421
+ payload: intentEventPayload
3422
+ };
3423
+ this.logger?.info(`Sending 'intentEvent' message: ${JSON.stringify(intentEventMsg)}`);
3424
+ this.sendBridgeMessage(intentEventMsg);
3425
+ const intentResultReceivedPromise = wrapPromise();
3426
+ this.intentHandlerResultPromiseCollection[eventUuid] = intentResultReceivedPromise;
3427
+ this.logger?.info(`Waiting for intent result for eventUuid: ${eventUuid}`);
3428
+ const result = await intentResultReceivedPromise.promise;
3429
+ const resultToReturn = this.getIntentResultToReturn(result);
3430
+ this.logger?.info(`Returning intent result: ${JSON.stringify(resultToReturn)} for eventUuid: ${eventUuid}`);
3431
+ delete this.intentHandlerResultPromiseCollection[eventUuid];
3432
+ return resultToReturn;
3433
+ };
3434
+ const listenerUUID = nanoid();
3435
+ const listener = await window.fdc3?.addIntentListener(payload.intent, handler);
3436
+ this.listenersCollection[listenerUUID] = listener;
3437
+ return { listenerUUID };
3438
+ }
3439
+ getIntentResultToReturn(result) {
3440
+ this.logger?.info(`Processing received intent result: ${JSON.stringify(result)}`);
3441
+ if (!result || (typeof result === "object" && !Object.keys(result).length)) {
3442
+ return undefined;
3443
+ }
3444
+ if (result.context) {
3445
+ return result.context;
3446
+ }
3447
+ if (result.channel) {
3448
+ return {
3449
+ id: result.channel.id,
3450
+ type: result.channel.type,
3451
+ displayMetadata: result.channel.displayMetadata,
3452
+ broadcast: async () => { },
3453
+ addContextListener: async () => { },
3454
+ getCurrentContext: async () => { }
3455
+ };
3456
+ }
3457
+ }
3458
+ async handleFindIntentRequest({ payload }) {
3459
+ const appIntent = await window.fdc3?.findIntent(payload.intent, payload.context, payload.resultType);
3460
+ return { appIntent };
3461
+ }
3462
+ async handleFindIntentsByContextRequest({ payload }) {
3463
+ const appIntents = await window.fdc3?.findIntentsByContext(payload.context, payload.resultType);
3464
+ return { appIntents };
3465
+ }
3466
+ async handleIntentListenerUnsubscribeRequest({ payload }) {
3467
+ const listener = this.listenersCollection[payload.listenerUUID];
3468
+ if (!listener) {
3469
+ return { error: "MalformedMessage", reason: `Cannot find listener with id ${payload.listenerUUID}` };
3470
+ }
3471
+ listener.unsubscribe();
3472
+ delete this.listenersCollection[payload.listenerUUID];
3473
+ return {};
3474
+ }
3475
+ async handleIntentResultRequest({ payload }) {
3476
+ this.logger?.info(`Received intent result request with payload: ${JSON.stringify(payload)}`);
3477
+ const intentEventUuid = payload.intentEventUuid;
3478
+ const intentEventResultPromise = this.intentHandlerResultPromiseCollection[intentEventUuid];
3479
+ if (!intentEventResultPromise) {
3480
+ this.logger?.error(`No intent handler result promise found for eventUuid: ${intentEventUuid}`);
3481
+ return { error: "MalformedMessage" };
3482
+ }
3483
+ this.logger?.info(`Resolving intent handler result promise for eventUuid: ${intentEventUuid} with result: ${JSON.stringify(payload.intentResult)}`);
3484
+ intentEventResultPromise.resolve(payload.intentResult);
3485
+ return {};
3486
+ }
3487
+ async handleRaiseIntentForContextRequest({ meta, payload }) {
3488
+ const intentResolution = await window.fdc3?.raiseIntentForContext(payload.context, payload.app);
3489
+ if (!intentResolution) {
3490
+ return { error: "IntentDeliveryFailed" };
3491
+ }
3492
+ this.logger?.info(`Saving intent resolution for requestUuid: ${meta.requestUuid}`);
3493
+ this.intentResolutionsCollection[meta.requestUuid] = intentResolution;
3494
+ const intentResolutionToReturn = { source: intentResolution.source, intent: intentResolution.intent };
3495
+ this.processRaiseIntentResultResponseAsync({
3496
+ type: "raiseIntentForContextRequest",
3497
+ payload,
3498
+ meta
3499
+ });
3500
+ return { intentResolution: intentResolutionToReturn };
3501
+ }
3502
+ async handleRaiseIntentRequest({ payload, meta }) {
3503
+ const intentResolution = await window.fdc3?.raiseIntent(payload.intent, payload.context, payload.app);
3504
+ if (!intentResolution) {
3505
+ return { error: "IntentDeliveryFailed" };
3506
+ }
3507
+ this.logger?.info(`Saving intent resolution for requestUuid: ${meta.requestUuid}`);
3508
+ this.intentResolutionsCollection[meta.requestUuid] = intentResolution;
3509
+ const intentResolutionToReturn = { source: intentResolution.source, intent: intentResolution.intent };
3510
+ this.processRaiseIntentResultResponseAsync({
3511
+ type: "raiseIntentRequest",
3512
+ payload,
3513
+ meta
3514
+ });
3515
+ return { intentResolution: intentResolutionToReturn };
3516
+ }
3517
+ async handleRaiseIntentResultResponse({ payload, meta }) {
3518
+ this.logger?.info(`handleRaiseIntentResultResponse called with payload: ${JSON.stringify(payload)} and meta: ${JSON.stringify(meta)}`);
3519
+ const intentResolution = await this.intentResolutionsCollection[meta.requestUuid];
3520
+ if (!intentResolution) {
3521
+ this.logger?.info(`Did not find intent resolution for requestUuid: ${meta.requestUuid}`);
3522
+ return { error: "IntentDeliveryFailed" };
3523
+ }
3524
+ this.logger?.info(`Found intent resolution for requestUuid: ${meta.requestUuid}. Retrieving result...`);
3525
+ const result = await intentResolution.getResult();
3526
+ this.logger?.info(`Received intent result: ${JSON.stringify(result)}`);
3527
+ if (!result) {
3528
+ const intentStr = payload.intent ? "intent '" + payload.intent + "'" : "";
3529
+ const contextStr = payload.context ? "context type '" + payload.context + "'" : "";
3530
+ this.logger?.info(`Intent result is void for ${intentStr}${contextStr} and requestUuid: ${meta.requestUuid}`);
3531
+ return { intentResult: undefined };
3532
+ }
3533
+ const intentResult = this.extractRaiseIntentResult(result);
3534
+ this.logger?.info(`Extracted intent result: ${JSON.stringify(intentResult)}`);
3535
+ return intentResult;
3536
+ }
3537
+ extractRaiseIntentResult(receivedResult) {
3538
+ if (!receivedResult) {
3539
+ return { intentResult: undefined };
3540
+ }
3541
+ const isChannel = checkIfFDC3Channel(receivedResult);
3542
+ if (isChannel) {
3543
+ this.checkSetPrivateChanel(receivedResult);
3544
+ return { intentResult: { channel: JSON.parse(JSON.stringify(receivedResult)) } };
3545
+ }
3546
+ const isContext = checkIfFDC3Context(receivedResult);
3547
+ if (isContext) {
3548
+ return { intentResult: { context: receivedResult } };
3549
+ }
3550
+ if (receivedResult.error) {
3551
+ return { error: receivedResult.error };
3552
+ }
3553
+ return { error: "IntentDeliveryFailed" };
3554
+ }
3555
+ checkSetPrivateChanel(channel) {
3556
+ const isPrivate = channel.id.startsWith(privateChannelPrefix) && channel.type === "private";
3557
+ if (!isPrivate) {
3558
+ return;
3559
+ }
3560
+ this.addPrivateChannel(channel);
3561
+ }
3562
+ async processRaiseIntentResultResponseAsync({ payload, meta }) {
3563
+ this.logger?.warn("Processing raise intent result response asynchronously with payload: " + JSON.stringify(payload));
3564
+ const syntheticRequest = {
3565
+ type: "raiseIntentResultRequest",
3566
+ meta: {
3567
+ requestUuid: meta.requestUuid,
3568
+ source: meta.source,
3569
+ timestamp: new Date()
3570
+ },
3571
+ payload: payload
3572
+ };
3573
+ const response = await this.handleControl(syntheticRequest);
3574
+ this.logger?.info(`Sending raise intent result response: ${JSON.stringify(response)}`);
3575
+ this.sendBridgeMessage(response);
3576
+ }
3577
+ decorateResponse({ request, responseUuid, payload }) {
3578
+ return {
3579
+ type: this.operations[request.type].responseType,
3580
+ meta: {
3581
+ requestUuid: request.meta.requestUuid,
3582
+ responseUuid: responseUuid,
3583
+ source: request.meta.source,
3584
+ timestamp: new Date()
3585
+ },
3586
+ payload
3587
+ };
3588
+ }
3589
+ }
3590
+
3591
+ class IoC {
3592
+ _bridgeController;
3593
+ _ioController;
3594
+ _domainsController;
3595
+ _channelsController;
3596
+ _intentsController;
3597
+ _applicationsController;
3598
+ get bridgeController() {
3599
+ if (!this._bridgeController) {
3600
+ this._bridgeController = new BridgeController(this.ioController, this);
3601
+ }
3602
+ return this._bridgeController;
3603
+ }
3604
+ get ioController() {
3605
+ if (!this._ioController) {
3606
+ this._ioController = new IOController();
3607
+ }
3608
+ return this._ioController;
3609
+ }
3610
+ createMessageChannel() {
3611
+ return new MessageChannel();
3612
+ }
3613
+ get domainsController() {
3614
+ if (!this._domainsController) {
3615
+ this._domainsController = new DomainsController(this.channelsController, this.intentsController, this.applicationsController, this.ioController);
3616
+ }
3617
+ return this._domainsController;
3618
+ }
3619
+ get channelsController() {
3620
+ if (!this._channelsController) {
3621
+ this._channelsController = new ChannelsController(this.bridgeController.sendMessage.bind(this.bridgeController), this.ioController.getLogger("channels.controller"));
3622
+ }
3623
+ return this._channelsController;
3624
+ }
3625
+ get intentsController() {
3626
+ if (!this._intentsController) {
3627
+ this._intentsController = new IntentsController(this.bridgeController.sendMessage.bind(this.bridgeController), this.channelsController.addPrivateChannel.bind(this.channelsController), this.ioController.getLogger("intents.controller"));
3628
+ }
3629
+ return this._intentsController;
3630
+ }
3631
+ get applicationsController() {
3632
+ if (!this._applicationsController) {
3633
+ this._applicationsController = new ApplicationsController(this.ioController.getLogger("applications.controller"));
3634
+ }
3635
+ return this._applicationsController;
3636
+ }
3637
+ }
3638
+
3639
+ var version = "1.0.0";
3640
+
3641
+ window.fdc3WebBridgeInfo = {
3642
+ version
3643
+ };
3644
+ const start = () => {
3645
+ const ioc = new IoC();
3646
+ ioc.bridgeController.configure();
3647
+ };
3648
+ start();
3649
+ //# sourceMappingURL=fdc3-web-bridge.es.js.map