@interopio/utils 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,1121 @@
1
+ const connectBrowserAppProps = ["name", "title", "version", "customProperties", "icon", "caption", "type"];
2
+ const fdc3v2AppProps = ["appId", "name", "type", "details", "version", "title", "tooltip", "lang", "description", "categories", "icons", "screenshots", "contactEmail", "moreInfo", "publisher", "customConfig", "hostManifests", "interop", "localizedVersions"];
3
+
4
+ /**
5
+ * Wraps values in an `Ok` type.
6
+ *
7
+ * Example: `ok(5) // => {ok: true, result: 5}`
8
+ */
9
+ var ok = function (result) { return ({ ok: true, result: result }); };
10
+ /**
11
+ * Wraps errors in an `Err` type.
12
+ *
13
+ * Example: `err('on fire') // => {ok: false, error: 'on fire'}`
14
+ */
15
+ var err = function (error) { return ({ ok: false, error: error }); };
16
+ /**
17
+ * Create a `Promise` that either resolves with the result of `Ok` or rejects
18
+ * with the error of `Err`.
19
+ */
20
+ var asPromise = function (r) {
21
+ return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error);
22
+ };
23
+ /**
24
+ * Unwraps a `Result` and returns either the result of an `Ok`, or
25
+ * `defaultValue`.
26
+ *
27
+ * Example:
28
+ * ```
29
+ * Result.withDefault(5, number().run(json))
30
+ * ```
31
+ *
32
+ * It would be nice if `Decoder` had an instance method that mirrored this
33
+ * function. Such a method would look something like this:
34
+ * ```
35
+ * class Decoder<A> {
36
+ * runWithDefault = (defaultValue: A, json: any): A =>
37
+ * Result.withDefault(defaultValue, this.run(json));
38
+ * }
39
+ *
40
+ * number().runWithDefault(5, json)
41
+ * ```
42
+ * Unfortunately, the type of `defaultValue: A` on the method causes issues
43
+ * with type inference on the `object` decoder in some situations. While these
44
+ * inference issues can be solved by providing the optional type argument for
45
+ * `object`s, the extra trouble and confusion doesn't seem worth it.
46
+ */
47
+ var withDefault = function (defaultValue, r) {
48
+ return r.ok === true ? r.result : defaultValue;
49
+ };
50
+ /**
51
+ * Return the successful result, or throw an error.
52
+ */
53
+ var withException = function (r) {
54
+ if (r.ok === true) {
55
+ return r.result;
56
+ }
57
+ else {
58
+ throw r.error;
59
+ }
60
+ };
61
+ /**
62
+ * Apply `f` to the result of an `Ok`, or pass the error through.
63
+ */
64
+ var map = function (f, r) {
65
+ return r.ok === true ? ok(f(r.result)) : r;
66
+ };
67
+ /**
68
+ * Apply `f` to the result of two `Ok`s, or pass an error through. If both
69
+ * `Result`s are errors then the first one is returned.
70
+ */
71
+ var map2 = function (f, ar, br) {
72
+ return ar.ok === false ? ar :
73
+ br.ok === false ? br :
74
+ ok(f(ar.result, br.result));
75
+ };
76
+ /**
77
+ * Apply `f` to the error of an `Err`, or pass the success through.
78
+ */
79
+ var mapError = function (f, r) {
80
+ return r.ok === true ? r : err(f(r.error));
81
+ };
82
+ /**
83
+ * Chain together a sequence of computations that may fail, similar to a
84
+ * `Promise`. If the first computation fails then the error will propagate
85
+ * through. If it succeeds, then `f` will be applied to the value, returning a
86
+ * new `Result`.
87
+ */
88
+ var andThen = function (f, r) {
89
+ return r.ok === true ? f(r.result) : r;
90
+ };
91
+
92
+ /*! *****************************************************************************
93
+ Copyright (c) Microsoft Corporation.
94
+
95
+ Permission to use, copy, modify, and/or distribute this software for any
96
+ purpose with or without fee is hereby granted.
97
+
98
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
99
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
100
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
101
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
102
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
103
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
104
+ PERFORMANCE OF THIS SOFTWARE.
105
+ ***************************************************************************** */
106
+ /* global Reflect, Promise */
107
+
108
+
109
+
110
+ var __assign = function() {
111
+ __assign = Object.assign || function __assign(t) {
112
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
113
+ s = arguments[i];
114
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
115
+ }
116
+ return t;
117
+ };
118
+ return __assign.apply(this, arguments);
119
+ };
120
+
121
+ function __rest(s, e) {
122
+ var t = {};
123
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
124
+ t[p] = s[p];
125
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
126
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
127
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
128
+ t[p[i]] = s[p[i]];
129
+ }
130
+ return t;
131
+ }
132
+
133
+ function isEqual(a, b) {
134
+ if (a === b) {
135
+ return true;
136
+ }
137
+ if (a === null && b === null) {
138
+ return true;
139
+ }
140
+ if (typeof (a) !== typeof (b)) {
141
+ return false;
142
+ }
143
+ if (typeof (a) === 'object') {
144
+ // Array
145
+ if (Array.isArray(a)) {
146
+ if (!Array.isArray(b)) {
147
+ return false;
148
+ }
149
+ if (a.length !== b.length) {
150
+ return false;
151
+ }
152
+ for (var i = 0; i < a.length; i++) {
153
+ if (!isEqual(a[i], b[i])) {
154
+ return false;
155
+ }
156
+ }
157
+ return true;
158
+ }
159
+ // Hash table
160
+ var keys = Object.keys(a);
161
+ if (keys.length !== Object.keys(b).length) {
162
+ return false;
163
+ }
164
+ for (var i = 0; i < keys.length; i++) {
165
+ if (!b.hasOwnProperty(keys[i])) {
166
+ return false;
167
+ }
168
+ if (!isEqual(a[keys[i]], b[keys[i]])) {
169
+ return false;
170
+ }
171
+ }
172
+ return true;
173
+ }
174
+ }
175
+ /*
176
+ * Helpers
177
+ */
178
+ var isJsonArray = function (json) { return Array.isArray(json); };
179
+ var isJsonObject = function (json) {
180
+ return typeof json === 'object' && json !== null && !isJsonArray(json);
181
+ };
182
+ var typeString = function (json) {
183
+ switch (typeof json) {
184
+ case 'string':
185
+ return 'a string';
186
+ case 'number':
187
+ return 'a number';
188
+ case 'boolean':
189
+ return 'a boolean';
190
+ case 'undefined':
191
+ return 'undefined';
192
+ case 'object':
193
+ if (json instanceof Array) {
194
+ return 'an array';
195
+ }
196
+ else if (json === null) {
197
+ return 'null';
198
+ }
199
+ else {
200
+ return 'an object';
201
+ }
202
+ default:
203
+ return JSON.stringify(json);
204
+ }
205
+ };
206
+ var expectedGot = function (expected, got) {
207
+ return "expected " + expected + ", got " + typeString(got);
208
+ };
209
+ var printPath = function (paths) {
210
+ return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join('');
211
+ };
212
+ var prependAt = function (newAt, _a) {
213
+ var at = _a.at, rest = __rest(_a, ["at"]);
214
+ return (__assign({ at: newAt + (at || '') }, rest));
215
+ };
216
+ /**
217
+ * Decoders transform json objects with unknown structure into known and
218
+ * verified forms. You can create objects of type `Decoder<A>` with either the
219
+ * primitive decoder functions, such as `boolean()` and `string()`, or by
220
+ * applying higher-order decoders to the primitives, such as `array(boolean())`
221
+ * or `dict(string())`.
222
+ *
223
+ * Each of the decoder functions are available both as a static method on
224
+ * `Decoder` and as a function alias -- for example the string decoder is
225
+ * defined at `Decoder.string()`, but is also aliased to `string()`. Using the
226
+ * function aliases exported with the library is recommended.
227
+ *
228
+ * `Decoder` exposes a number of 'run' methods, which all decode json in the
229
+ * same way, but communicate success and failure in different ways. The `map`
230
+ * and `andThen` methods modify decoders without having to call a 'run' method.
231
+ *
232
+ * Alternatively, the main decoder `run()` method returns an object of type
233
+ * `Result<A, DecoderError>`. This library provides a number of helper
234
+ * functions for dealing with the `Result` type, so you can do all the same
235
+ * things with a `Result` as with the decoder methods.
236
+ */
237
+ var Decoder = /** @class */ (function () {
238
+ /**
239
+ * The Decoder class constructor is kept private to separate the internal
240
+ * `decode` function from the external `run` function. The distinction
241
+ * between the two functions is that `decode` returns a
242
+ * `Partial<DecoderError>` on failure, which contains an unfinished error
243
+ * report. When `run` is called on a decoder, the relevant series of `decode`
244
+ * calls is made, and then on failure the resulting `Partial<DecoderError>`
245
+ * is turned into a `DecoderError` by filling in the missing information.
246
+ *
247
+ * While hiding the constructor may seem restrictive, leveraging the
248
+ * provided decoder combinators and helper functions such as
249
+ * `andThen` and `map` should be enough to build specialized decoders as
250
+ * needed.
251
+ */
252
+ function Decoder(decode) {
253
+ var _this = this;
254
+ this.decode = decode;
255
+ /**
256
+ * Run the decoder and return a `Result` with either the decoded value or a
257
+ * `DecoderError` containing the json input, the location of the error, and
258
+ * the error message.
259
+ *
260
+ * Examples:
261
+ * ```
262
+ * number().run(12)
263
+ * // => {ok: true, result: 12}
264
+ *
265
+ * string().run(9001)
266
+ * // =>
267
+ * // {
268
+ * // ok: false,
269
+ * // error: {
270
+ * // kind: 'DecoderError',
271
+ * // input: 9001,
272
+ * // at: 'input',
273
+ * // message: 'expected a string, got 9001'
274
+ * // }
275
+ * // }
276
+ * ```
277
+ */
278
+ this.run = function (json) {
279
+ return mapError(function (error) { return ({
280
+ kind: 'DecoderError',
281
+ input: json,
282
+ at: 'input' + (error.at || ''),
283
+ message: error.message || ''
284
+ }); }, _this.decode(json));
285
+ };
286
+ /**
287
+ * Run the decoder as a `Promise`.
288
+ */
289
+ this.runPromise = function (json) { return asPromise(_this.run(json)); };
290
+ /**
291
+ * Run the decoder and return the value on success, or throw an exception
292
+ * with a formatted error string.
293
+ */
294
+ this.runWithException = function (json) { return withException(_this.run(json)); };
295
+ /**
296
+ * Construct a new decoder that applies a transformation to the decoded
297
+ * result. If the decoder succeeds then `f` will be applied to the value. If
298
+ * it fails the error will propagated through.
299
+ *
300
+ * Example:
301
+ * ```
302
+ * number().map(x => x * 5).run(10)
303
+ * // => {ok: true, result: 50}
304
+ * ```
305
+ */
306
+ this.map = function (f) {
307
+ return new Decoder(function (json) { return map(f, _this.decode(json)); });
308
+ };
309
+ /**
310
+ * Chain together a sequence of decoders. The first decoder will run, and
311
+ * then the function will determine what decoder to run second. If the result
312
+ * of the first decoder succeeds then `f` will be applied to the decoded
313
+ * value. If it fails the error will propagate through.
314
+ *
315
+ * This is a very powerful method -- it can act as both the `map` and `where`
316
+ * methods, can improve error messages for edge cases, and can be used to
317
+ * make a decoder for custom types.
318
+ *
319
+ * Example of adding an error message:
320
+ * ```
321
+ * const versionDecoder = valueAt(['version'], number());
322
+ * const infoDecoder3 = object({a: boolean()});
323
+ *
324
+ * const decoder = versionDecoder.andThen(version => {
325
+ * switch (version) {
326
+ * case 3:
327
+ * return infoDecoder3;
328
+ * default:
329
+ * return fail(`Unable to decode info, version ${version} is not supported.`);
330
+ * }
331
+ * });
332
+ *
333
+ * decoder.run({version: 3, a: true})
334
+ * // => {ok: true, result: {a: true}}
335
+ *
336
+ * decoder.run({version: 5, x: 'abc'})
337
+ * // =>
338
+ * // {
339
+ * // ok: false,
340
+ * // error: {... message: 'Unable to decode info, version 5 is not supported.'}
341
+ * // }
342
+ * ```
343
+ *
344
+ * Example of decoding a custom type:
345
+ * ```
346
+ * // nominal type for arrays with a length of at least one
347
+ * type NonEmptyArray<T> = T[] & { __nonEmptyArrayBrand__: void };
348
+ *
349
+ * const nonEmptyArrayDecoder = <T>(values: Decoder<T>): Decoder<NonEmptyArray<T>> =>
350
+ * array(values).andThen(arr =>
351
+ * arr.length > 0
352
+ * ? succeed(createNonEmptyArray(arr))
353
+ * : fail(`expected a non-empty array, got an empty array`)
354
+ * );
355
+ * ```
356
+ */
357
+ this.andThen = function (f) {
358
+ return new Decoder(function (json) {
359
+ return andThen(function (value) { return f(value).decode(json); }, _this.decode(json));
360
+ });
361
+ };
362
+ /**
363
+ * Add constraints to a decoder _without_ changing the resulting type. The
364
+ * `test` argument is a predicate function which returns true for valid
365
+ * inputs. When `test` fails on an input, the decoder fails with the given
366
+ * `errorMessage`.
367
+ *
368
+ * ```
369
+ * const chars = (length: number): Decoder<string> =>
370
+ * string().where(
371
+ * (s: string) => s.length === length,
372
+ * `expected a string of length ${length}`
373
+ * );
374
+ *
375
+ * chars(5).run('12345')
376
+ * // => {ok: true, result: '12345'}
377
+ *
378
+ * chars(2).run('HELLO')
379
+ * // => {ok: false, error: {... message: 'expected a string of length 2'}}
380
+ *
381
+ * chars(12).run(true)
382
+ * // => {ok: false, error: {... message: 'expected a string, got a boolean'}}
383
+ * ```
384
+ */
385
+ this.where = function (test, errorMessage) {
386
+ return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); });
387
+ };
388
+ }
389
+ /**
390
+ * Decoder primitive that validates strings, and fails on all other input.
391
+ */
392
+ Decoder.string = function () {
393
+ return new Decoder(function (json) {
394
+ return typeof json === 'string'
395
+ ? ok(json)
396
+ : err({ message: expectedGot('a string', json) });
397
+ });
398
+ };
399
+ /**
400
+ * Decoder primitive that validates numbers, and fails on all other input.
401
+ */
402
+ Decoder.number = function () {
403
+ return new Decoder(function (json) {
404
+ return typeof json === 'number'
405
+ ? ok(json)
406
+ : err({ message: expectedGot('a number', json) });
407
+ });
408
+ };
409
+ /**
410
+ * Decoder primitive that validates booleans, and fails on all other input.
411
+ */
412
+ Decoder.boolean = function () {
413
+ return new Decoder(function (json) {
414
+ return typeof json === 'boolean'
415
+ ? ok(json)
416
+ : err({ message: expectedGot('a boolean', json) });
417
+ });
418
+ };
419
+ Decoder.constant = function (value) {
420
+ return new Decoder(function (json) {
421
+ return isEqual(json, value)
422
+ ? ok(value)
423
+ : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) });
424
+ });
425
+ };
426
+ Decoder.object = function (decoders) {
427
+ return new Decoder(function (json) {
428
+ if (isJsonObject(json) && decoders) {
429
+ var obj = {};
430
+ for (var key in decoders) {
431
+ if (decoders.hasOwnProperty(key)) {
432
+ var r = decoders[key].decode(json[key]);
433
+ if (r.ok === true) {
434
+ // tslint:disable-next-line:strict-type-predicates
435
+ if (r.result !== undefined) {
436
+ obj[key] = r.result;
437
+ }
438
+ }
439
+ else if (json[key] === undefined) {
440
+ return err({ message: "the key '" + key + "' is required but was not present" });
441
+ }
442
+ else {
443
+ return err(prependAt("." + key, r.error));
444
+ }
445
+ }
446
+ }
447
+ return ok(obj);
448
+ }
449
+ else if (isJsonObject(json)) {
450
+ return ok(json);
451
+ }
452
+ else {
453
+ return err({ message: expectedGot('an object', json) });
454
+ }
455
+ });
456
+ };
457
+ Decoder.array = function (decoder) {
458
+ return new Decoder(function (json) {
459
+ if (isJsonArray(json) && decoder) {
460
+ var decodeValue_1 = function (v, i) {
461
+ return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v));
462
+ };
463
+ return json.reduce(function (acc, v, i) {
464
+ return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i));
465
+ }, ok([]));
466
+ }
467
+ else if (isJsonArray(json)) {
468
+ return ok(json);
469
+ }
470
+ else {
471
+ return err({ message: expectedGot('an array', json) });
472
+ }
473
+ });
474
+ };
475
+ Decoder.tuple = function (decoders) {
476
+ return new Decoder(function (json) {
477
+ if (isJsonArray(json)) {
478
+ if (json.length !== decoders.length) {
479
+ return err({
480
+ message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length
481
+ });
482
+ }
483
+ var result = [];
484
+ for (var i = 0; i < decoders.length; i++) {
485
+ var nth = decoders[i].decode(json[i]);
486
+ if (nth.ok) {
487
+ result[i] = nth.result;
488
+ }
489
+ else {
490
+ return err(prependAt("[" + i + "]", nth.error));
491
+ }
492
+ }
493
+ return ok(result);
494
+ }
495
+ else {
496
+ return err({ message: expectedGot("a tuple of length " + decoders.length, json) });
497
+ }
498
+ });
499
+ };
500
+ Decoder.union = function (ad, bd) {
501
+ var decoders = [];
502
+ for (var _i = 2; _i < arguments.length; _i++) {
503
+ decoders[_i - 2] = arguments[_i];
504
+ }
505
+ return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders));
506
+ };
507
+ Decoder.intersection = function (ad, bd) {
508
+ var ds = [];
509
+ for (var _i = 2; _i < arguments.length; _i++) {
510
+ ds[_i - 2] = arguments[_i];
511
+ }
512
+ return new Decoder(function (json) {
513
+ return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({}));
514
+ });
515
+ };
516
+ /**
517
+ * Escape hatch to bypass validation. Always succeeds and types the result as
518
+ * `any`. Useful for defining decoders incrementally, particularly for
519
+ * complex objects.
520
+ *
521
+ * Example:
522
+ * ```
523
+ * interface User {
524
+ * name: string;
525
+ * complexUserData: ComplexType;
526
+ * }
527
+ *
528
+ * const userDecoder: Decoder<User> = object({
529
+ * name: string(),
530
+ * complexUserData: anyJson()
531
+ * });
532
+ * ```
533
+ */
534
+ Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); };
535
+ /**
536
+ * Decoder identity function which always succeeds and types the result as
537
+ * `unknown`.
538
+ */
539
+ Decoder.unknownJson = function () {
540
+ return new Decoder(function (json) { return ok(json); });
541
+ };
542
+ /**
543
+ * Decoder for json objects where the keys are unknown strings, but the values
544
+ * should all be of the same type.
545
+ *
546
+ * Example:
547
+ * ```
548
+ * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37});
549
+ * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}}
550
+ * ```
551
+ */
552
+ Decoder.dict = function (decoder) {
553
+ return new Decoder(function (json) {
554
+ if (isJsonObject(json)) {
555
+ var obj = {};
556
+ for (var key in json) {
557
+ if (json.hasOwnProperty(key)) {
558
+ var r = decoder.decode(json[key]);
559
+ if (r.ok === true) {
560
+ obj[key] = r.result;
561
+ }
562
+ else {
563
+ return err(prependAt("." + key, r.error));
564
+ }
565
+ }
566
+ }
567
+ return ok(obj);
568
+ }
569
+ else {
570
+ return err({ message: expectedGot('an object', json) });
571
+ }
572
+ });
573
+ };
574
+ /**
575
+ * Decoder for values that may be `undefined`. This is primarily helpful for
576
+ * decoding interfaces with optional fields.
577
+ *
578
+ * Example:
579
+ * ```
580
+ * interface User {
581
+ * id: number;
582
+ * isOwner?: boolean;
583
+ * }
584
+ *
585
+ * const decoder: Decoder<User> = object({
586
+ * id: number(),
587
+ * isOwner: optional(boolean())
588
+ * });
589
+ * ```
590
+ */
591
+ Decoder.optional = function (decoder) {
592
+ return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); });
593
+ };
594
+ /**
595
+ * Decoder that attempts to run each decoder in `decoders` and either succeeds
596
+ * with the first successful decoder, or fails after all decoders have failed.
597
+ *
598
+ * Note that `oneOf` expects the decoders to all have the same return type,
599
+ * while `union` creates a decoder for the union type of all the input
600
+ * decoders.
601
+ *
602
+ * Examples:
603
+ * ```
604
+ * oneOf(string(), number().map(String))
605
+ * oneOf(constant('start'), constant('stop'), succeed('unknown'))
606
+ * ```
607
+ */
608
+ Decoder.oneOf = function () {
609
+ var decoders = [];
610
+ for (var _i = 0; _i < arguments.length; _i++) {
611
+ decoders[_i] = arguments[_i];
612
+ }
613
+ return new Decoder(function (json) {
614
+ var errors = [];
615
+ for (var i = 0; i < decoders.length; i++) {
616
+ var r = decoders[i].decode(json);
617
+ if (r.ok === true) {
618
+ return r;
619
+ }
620
+ else {
621
+ errors[i] = r.error;
622
+ }
623
+ }
624
+ var errorsList = errors
625
+ .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; })
626
+ .join('", "');
627
+ return err({
628
+ message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]"
629
+ });
630
+ });
631
+ };
632
+ /**
633
+ * Decoder that always succeeds with either the decoded value, or a fallback
634
+ * default value.
635
+ */
636
+ Decoder.withDefault = function (defaultValue, decoder) {
637
+ return new Decoder(function (json) {
638
+ return ok(withDefault(defaultValue, decoder.decode(json)));
639
+ });
640
+ };
641
+ /**
642
+ * Decoder that pulls a specific field out of a json structure, instead of
643
+ * decoding and returning the full structure. The `paths` array describes the
644
+ * object keys and array indices to traverse, so that values can be pulled out
645
+ * of a nested structure.
646
+ *
647
+ * Example:
648
+ * ```
649
+ * const decoder = valueAt(['a', 'b', 0], string());
650
+ *
651
+ * decoder.run({a: {b: ['surprise!']}})
652
+ * // => {ok: true, result: 'surprise!'}
653
+ *
654
+ * decoder.run({a: {x: 'cats'}})
655
+ * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}}
656
+ * ```
657
+ *
658
+ * Note that the `decoder` is ran on the value found at the last key in the
659
+ * path, even if the last key is not found. This allows the `optional`
660
+ * decoder to succeed when appropriate.
661
+ * ```
662
+ * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string()));
663
+ *
664
+ * optionalDecoder.run({a: {b: {c: 'surprise!'}}})
665
+ * // => {ok: true, result: 'surprise!'}
666
+ *
667
+ * optionalDecoder.run({a: {b: 'cats'}})
668
+ * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'}
669
+ *
670
+ * optionalDecoder.run({a: {b: {z: 1}}})
671
+ * // => {ok: true, result: undefined}
672
+ * ```
673
+ */
674
+ Decoder.valueAt = function (paths, decoder) {
675
+ return new Decoder(function (json) {
676
+ var jsonAtPath = json;
677
+ for (var i = 0; i < paths.length; i++) {
678
+ if (jsonAtPath === undefined) {
679
+ return err({
680
+ at: printPath(paths.slice(0, i + 1)),
681
+ message: 'path does not exist'
682
+ });
683
+ }
684
+ else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) {
685
+ return err({
686
+ at: printPath(paths.slice(0, i + 1)),
687
+ message: expectedGot('an object', jsonAtPath)
688
+ });
689
+ }
690
+ else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) {
691
+ return err({
692
+ at: printPath(paths.slice(0, i + 1)),
693
+ message: expectedGot('an array', jsonAtPath)
694
+ });
695
+ }
696
+ else {
697
+ jsonAtPath = jsonAtPath[paths[i]];
698
+ }
699
+ }
700
+ return mapError(function (error) {
701
+ return jsonAtPath === undefined
702
+ ? { at: printPath(paths), message: 'path does not exist' }
703
+ : prependAt(printPath(paths), error);
704
+ }, decoder.decode(jsonAtPath));
705
+ });
706
+ };
707
+ /**
708
+ * Decoder that ignores the input json and always succeeds with `fixedValue`.
709
+ */
710
+ Decoder.succeed = function (fixedValue) {
711
+ return new Decoder(function (json) { return ok(fixedValue); });
712
+ };
713
+ /**
714
+ * Decoder that ignores the input json and always fails with `errorMessage`.
715
+ */
716
+ Decoder.fail = function (errorMessage) {
717
+ return new Decoder(function (json) { return err({ message: errorMessage }); });
718
+ };
719
+ /**
720
+ * Decoder that allows for validating recursive data structures. Unlike with
721
+ * functions, decoders assigned to variables can't reference themselves
722
+ * before they are fully defined. We can avoid prematurely referencing the
723
+ * decoder by wrapping it in a function that won't be called until use, at
724
+ * which point the decoder has been defined.
725
+ *
726
+ * Example:
727
+ * ```
728
+ * interface Comment {
729
+ * msg: string;
730
+ * replies: Comment[];
731
+ * }
732
+ *
733
+ * const decoder: Decoder<Comment> = object({
734
+ * msg: string(),
735
+ * replies: lazy(() => array(decoder))
736
+ * });
737
+ * ```
738
+ */
739
+ Decoder.lazy = function (mkDecoder) {
740
+ return new Decoder(function (json) { return mkDecoder().decode(json); });
741
+ };
742
+ return Decoder;
743
+ }());
744
+
745
+ /* tslint:disable:variable-name */
746
+ /** See `Decoder.string` */
747
+ var string = Decoder.string;
748
+ /** See `Decoder.number` */
749
+ var number = Decoder.number;
750
+ /** See `Decoder.boolean` */
751
+ var boolean = Decoder.boolean;
752
+ /** See `Decoder.anyJson` */
753
+ var anyJson = Decoder.anyJson;
754
+ /** See `Decoder.unknownJson` */
755
+ Decoder.unknownJson;
756
+ /** See `Decoder.constant` */
757
+ var constant = Decoder.constant;
758
+ /** See `Decoder.object` */
759
+ var object = Decoder.object;
760
+ /** See `Decoder.array` */
761
+ var array = Decoder.array;
762
+ /** See `Decoder.tuple` */
763
+ Decoder.tuple;
764
+ /** See `Decoder.dict` */
765
+ var dict = Decoder.dict;
766
+ /** See `Decoder.optional` */
767
+ var optional = Decoder.optional;
768
+ /** See `Decoder.oneOf` */
769
+ var oneOf = Decoder.oneOf;
770
+ /** See `Decoder.union` */
771
+ Decoder.union;
772
+ /** See `Decoder.intersection` */
773
+ Decoder.intersection;
774
+ /** See `Decoder.withDefault` */
775
+ Decoder.withDefault;
776
+ /** See `Decoder.valueAt` */
777
+ Decoder.valueAt;
778
+ /** See `Decoder.succeed` */
779
+ Decoder.succeed;
780
+ /** See `Decoder.fail` */
781
+ Decoder.fail;
782
+ /** See `Decoder.lazy` */
783
+ var lazy = Decoder.lazy;
784
+
785
+ const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string");
786
+ const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number");
787
+
788
+ const intentDefinitionDecoder = object({
789
+ name: nonEmptyStringDecoder,
790
+ displayName: optional(string()),
791
+ contexts: optional(array(string())),
792
+ customConfig: optional(object())
793
+ });
794
+ const v2TypeDecoder = oneOf(constant("web"), constant("native"), constant("citrix"), constant("onlineNative"), constant("other"));
795
+ const v2DetailsDecoder = object({
796
+ url: nonEmptyStringDecoder
797
+ });
798
+ const v2IconDecoder = object({
799
+ src: nonEmptyStringDecoder,
800
+ size: optional(nonEmptyStringDecoder),
801
+ type: optional(nonEmptyStringDecoder)
802
+ });
803
+ const v2ScreenshotDecoder = object({
804
+ src: nonEmptyStringDecoder,
805
+ size: optional(nonEmptyStringDecoder),
806
+ type: optional(nonEmptyStringDecoder),
807
+ label: optional(nonEmptyStringDecoder)
808
+ });
809
+ const v2ListensForIntentDecoder = object({
810
+ contexts: array(nonEmptyStringDecoder),
811
+ displayName: optional(nonEmptyStringDecoder),
812
+ resultType: optional(nonEmptyStringDecoder),
813
+ customConfig: optional(anyJson())
814
+ });
815
+ const v2IntentsDecoder = object({
816
+ listensFor: optional(dict(v2ListensForIntentDecoder)),
817
+ raises: optional(dict(array(nonEmptyStringDecoder)))
818
+ });
819
+ const v2UserChannelDecoder = object({
820
+ broadcasts: optional(array(nonEmptyStringDecoder)),
821
+ listensFor: optional(array(nonEmptyStringDecoder))
822
+ });
823
+ const v2AppChannelDecoder = object({
824
+ name: nonEmptyStringDecoder,
825
+ description: optional(nonEmptyStringDecoder),
826
+ broadcasts: optional(array(nonEmptyStringDecoder)),
827
+ listensFor: optional(array(nonEmptyStringDecoder))
828
+ });
829
+ const v2InteropDecoder = object({
830
+ intents: optional(v2IntentsDecoder),
831
+ userChannels: optional(v2UserChannelDecoder),
832
+ appChannels: optional(array(v2AppChannelDecoder))
833
+ });
834
+ const glue42ApplicationDetailsDecoder = object({
835
+ url: nonEmptyStringDecoder,
836
+ top: optional(number()),
837
+ left: optional(number()),
838
+ width: optional(nonNegativeNumberDecoder),
839
+ height: optional(nonNegativeNumberDecoder)
840
+ });
841
+ const glue42HostManifestsBrowserDecoder = object({
842
+ name: optional(nonEmptyStringDecoder),
843
+ type: optional(nonEmptyStringDecoder.where((s) => s === "window", "Expected a value of window")),
844
+ title: optional(nonEmptyStringDecoder),
845
+ version: optional(nonEmptyStringDecoder),
846
+ customProperties: optional(anyJson()),
847
+ icon: optional(string()),
848
+ caption: optional(string()),
849
+ details: optional(glue42ApplicationDetailsDecoder),
850
+ intents: optional(array(intentDefinitionDecoder)),
851
+ hidden: optional(boolean())
852
+ });
853
+ const hostManifestsBrowserDecoder = oneOf(object({
854
+ "Glue42": oneOf(glue42HostManifestsBrowserDecoder, anyJson())
855
+ }), anyJson());
856
+ const v1DefinitionDecoder = object({
857
+ name: nonEmptyStringDecoder,
858
+ appId: nonEmptyStringDecoder,
859
+ title: optional(nonEmptyStringDecoder),
860
+ version: optional(nonEmptyStringDecoder),
861
+ manifest: nonEmptyStringDecoder,
862
+ manifestType: nonEmptyStringDecoder,
863
+ tooltip: optional(nonEmptyStringDecoder),
864
+ description: optional(nonEmptyStringDecoder),
865
+ contactEmail: optional(nonEmptyStringDecoder),
866
+ supportEmail: optional(nonEmptyStringDecoder),
867
+ publisher: optional(nonEmptyStringDecoder),
868
+ images: optional(array(object({ url: optional(nonEmptyStringDecoder) }))),
869
+ icons: optional(array(object({ icon: optional(nonEmptyStringDecoder) }))),
870
+ customConfig: anyJson(),
871
+ intents: optional(array(intentDefinitionDecoder))
872
+ });
873
+ const v2DefinitionDecoder = object({
874
+ appId: nonEmptyStringDecoder,
875
+ name: nonEmptyStringDecoder,
876
+ type: v2TypeDecoder,
877
+ details: v2DetailsDecoder,
878
+ version: optional(nonEmptyStringDecoder),
879
+ title: optional(nonEmptyStringDecoder),
880
+ tooltip: optional(nonEmptyStringDecoder),
881
+ lang: optional(nonEmptyStringDecoder),
882
+ description: optional(nonEmptyStringDecoder),
883
+ categories: optional(array(nonEmptyStringDecoder)),
884
+ icons: optional(array(v2IconDecoder)),
885
+ screenshots: optional(array(v2ScreenshotDecoder)),
886
+ contactEmail: optional(nonEmptyStringDecoder),
887
+ supportEmail: optional(nonEmptyStringDecoder),
888
+ moreInfo: optional(nonEmptyStringDecoder),
889
+ publisher: optional(nonEmptyStringDecoder),
890
+ customConfig: optional(array(anyJson())),
891
+ hostManifests: optional(hostManifestsBrowserDecoder),
892
+ interop: optional(v2InteropDecoder),
893
+ localizedVersions: optional(lazy(() => dict(v2DefinitionDecoder)))
894
+ });
895
+ const allDefinitionsDecoder = oneOf(v1DefinitionDecoder, v2DefinitionDecoder);
896
+
897
+ const parseDecoderErrorToStringMessage = (error) => {
898
+ return `${error.kind} at ${error.at}: ${JSON.stringify(error.input)}. Reason - ${error.message}`;
899
+ };
900
+
901
+ class FDC3Service {
902
+ constructor() {
903
+ this.fdc3ToDesktopDefinitionType = {
904
+ web: "window",
905
+ native: "exe",
906
+ citrix: "citrix",
907
+ onlineNative: "clickonce",
908
+ other: "window"
909
+ };
910
+ }
911
+ toApi() {
912
+ return {
913
+ isFdc3Definition: this.isFdc3Definition.bind(this),
914
+ parseToBrowserBaseAppData: this.parseToBrowserBaseAppData.bind(this),
915
+ parseToDesktopAppConfig: this.parseToDesktopAppConfig.bind(this)
916
+ };
917
+ }
918
+ isFdc3Definition(definition) {
919
+ const decodeRes = allDefinitionsDecoder.run(definition);
920
+ if (!decodeRes.ok) {
921
+ return { isFdc3: false };
922
+ }
923
+ if (definition.appId && definition.details) {
924
+ return { isFdc3: true, version: "2.0" };
925
+ }
926
+ if (definition.manifest) {
927
+ return { isFdc3: true, version: "1.2" };
928
+ }
929
+ return { isFdc3: false };
930
+ }
931
+ parseToBrowserBaseAppData(definition) {
932
+ var _a;
933
+ const { isFdc3, version } = this.isFdc3Definition(definition);
934
+ if (!isFdc3) {
935
+ throw new Error("The passed definition is not FDC3");
936
+ }
937
+ const decodeRes = allDefinitionsDecoder.run(definition);
938
+ if (!decodeRes.ok) {
939
+ throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`);
940
+ }
941
+ const userProperties = this.getUserPropertiesFromDefinition(definition, version);
942
+ const createOptions = { url: this.getUrl(definition, version) };
943
+ let baseApplicationData = {
944
+ name: definition.appId,
945
+ type: "window",
946
+ createOptions,
947
+ userProperties: Object.assign(Object.assign({}, userProperties), { intents: version === "1.2"
948
+ ? userProperties.intents
949
+ : this.getIntentsFromV2AppDefinition(definition), details: createOptions }),
950
+ title: definition.title,
951
+ version: definition.version,
952
+ icon: this.getIconFromDefinition(definition, version),
953
+ caption: definition.description,
954
+ fdc3: version === "2.0" ? Object.assign(Object.assign({}, definition), { definitionVersion: "2.0" }) : undefined,
955
+ };
956
+ if ((_a = definition.hostManifests) === null || _a === void 0 ? void 0 : _a["Glue42"]) {
957
+ const decodeRes = glue42HostManifestsBrowserDecoder.run(definition.hostManifests["Glue42"]);
958
+ if (!decodeRes.ok) {
959
+ throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`);
960
+ }
961
+ if (!Object.keys(decodeRes.result).length) {
962
+ throw new Error("Invalid 'hostManifests['Glue42]' key");
963
+ }
964
+ baseApplicationData = this.mergeBaseAppDataWithGlueManifest(baseApplicationData, decodeRes.result);
965
+ }
966
+ return baseApplicationData;
967
+ }
968
+ parseToDesktopAppConfig(definition) {
969
+ var _a, _b, _c;
970
+ const { isFdc3, version } = this.isFdc3Definition(definition);
971
+ if (!isFdc3) {
972
+ throw new Error("The passed definition is not FDC3");
973
+ }
974
+ const decodeRes = allDefinitionsDecoder.run(definition);
975
+ if (!decodeRes.ok) {
976
+ throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`);
977
+ }
978
+ if (version === "1.2") {
979
+ const fdc3v1Definition = definition;
980
+ return {
981
+ name: fdc3v1Definition.appId,
982
+ type: "window",
983
+ details: {
984
+ url: this.getUrl(definition, version)
985
+ },
986
+ version: fdc3v1Definition.version,
987
+ title: fdc3v1Definition.title,
988
+ tooltip: fdc3v1Definition.tooltip,
989
+ caption: fdc3v1Definition.description,
990
+ icon: (_a = fdc3v1Definition.icons) === null || _a === void 0 ? void 0 : _a[0].icon,
991
+ intents: fdc3v1Definition.intents,
992
+ customProperties: {
993
+ manifestType: fdc3v1Definition.manifestType,
994
+ images: fdc3v1Definition.images,
995
+ contactEmail: fdc3v1Definition.contactEmail,
996
+ supportEmail: fdc3v1Definition.supportEmail,
997
+ publisher: fdc3v1Definition.publisher,
998
+ icons: fdc3v1Definition.icons,
999
+ customConfig: fdc3v1Definition.customConfig
1000
+ }
1001
+ };
1002
+ }
1003
+ const fdc3v2Definition = definition;
1004
+ let desktopDefinition = {
1005
+ name: fdc3v2Definition.appId,
1006
+ type: this.fdc3ToDesktopDefinitionType[fdc3v2Definition.type],
1007
+ details: fdc3v2Definition.details,
1008
+ version: fdc3v2Definition.version,
1009
+ title: fdc3v2Definition.title,
1010
+ tooltip: fdc3v2Definition.tooltip,
1011
+ caption: fdc3v2Definition.description,
1012
+ icon: this.getIconFromDefinition(fdc3v2Definition, "2.0"),
1013
+ intents: this.getIntentsFromV2AppDefinition(fdc3v2Definition),
1014
+ fdc3: Object.assign(Object.assign({}, fdc3v2Definition), { definitionVersion: "2.0" })
1015
+ };
1016
+ if ((_b = fdc3v2Definition.hostManifests) === null || _b === void 0 ? void 0 : _b["Glue42"]) {
1017
+ if (typeof fdc3v2Definition.hostManifests["Glue42"] !== "object" || Array.isArray(fdc3v2Definition.hostManifests["Glue42"])) {
1018
+ throw new Error("Invalid 'hostManifests['Glue42]' key");
1019
+ }
1020
+ desktopDefinition = this.mergeDesktopConfigWithGlueManifest(desktopDefinition, (_c = fdc3v2Definition.hostManifests) === null || _c === void 0 ? void 0 : _c["Glue42"]);
1021
+ }
1022
+ return desktopDefinition;
1023
+ }
1024
+ getUserPropertiesFromDefinition(definition, version) {
1025
+ if (version === "1.2") {
1026
+ return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key)));
1027
+ }
1028
+ return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key) && !fdc3v2AppProps.includes(key)));
1029
+ }
1030
+ getUrl(definition, version) {
1031
+ var _a, _b;
1032
+ let url;
1033
+ if (version === "1.2") {
1034
+ const parsedManifest = JSON.parse(definition.manifest);
1035
+ url = ((_a = parsedManifest.details) === null || _a === void 0 ? void 0 : _a.url) || parsedManifest.url;
1036
+ }
1037
+ else {
1038
+ url = (_b = definition.details) === null || _b === void 0 ? void 0 : _b.url;
1039
+ }
1040
+ if (!url || typeof url !== "string") {
1041
+ throw new Error(`Invalid FDC3 ${version} definition. Provide valid 'url' under '${version === "1.2" ? "manifest" : "details"}' key`);
1042
+ }
1043
+ return url;
1044
+ }
1045
+ getIntentsFromV2AppDefinition(definition) {
1046
+ var _a, _b;
1047
+ const fdc3Intents = (_b = (_a = definition.interop) === null || _a === void 0 ? void 0 : _a.intents) === null || _b === void 0 ? void 0 : _b.listensFor;
1048
+ if (!fdc3Intents) {
1049
+ return;
1050
+ }
1051
+ const intents = Object.entries(fdc3Intents).map((fdc3Intent) => {
1052
+ const [intentName, intentData] = fdc3Intent;
1053
+ return Object.assign({ name: intentName }, intentData);
1054
+ });
1055
+ return intents;
1056
+ }
1057
+ getIconFromDefinition(definition, version) {
1058
+ var _a, _b, _c, _d;
1059
+ if (version === "1.2") {
1060
+ return ((_b = (_a = definition.icons) === null || _a === void 0 ? void 0 : _a.find((iconDef) => iconDef.icon)) === null || _b === void 0 ? void 0 : _b.icon) || undefined;
1061
+ }
1062
+ return ((_d = (_c = definition.icons) === null || _c === void 0 ? void 0 : _c.find((iconDef) => iconDef.src)) === null || _d === void 0 ? void 0 : _d.src) || undefined;
1063
+ }
1064
+ mergeBaseAppDataWithGlueManifest(baseAppData, hostManifestDefinition) {
1065
+ let baseApplicationDefinition = baseAppData;
1066
+ if (hostManifestDefinition.details) {
1067
+ const details = hostManifestDefinition.details;
1068
+ baseApplicationDefinition.createOptions = details;
1069
+ baseApplicationDefinition.userProperties.details = details;
1070
+ }
1071
+ if (Array.isArray(hostManifestDefinition.intents)) {
1072
+ baseApplicationDefinition.userProperties.intents = (baseApplicationDefinition.userProperties.intents || []).concat(hostManifestDefinition.intents);
1073
+ }
1074
+ baseApplicationDefinition = Object.assign(Object.assign({}, baseApplicationDefinition), hostManifestDefinition);
1075
+ delete baseApplicationDefinition.details;
1076
+ delete baseApplicationDefinition.intents;
1077
+ return baseApplicationDefinition;
1078
+ }
1079
+ mergeDesktopConfigWithGlueManifest(config, desktopDefinition) {
1080
+ let appConfig = Object.assign({}, config);
1081
+ appConfig = Object.assign(Object.assign({}, config), desktopDefinition);
1082
+ if (Array.isArray(desktopDefinition.intents)) {
1083
+ appConfig.intents = (config.intents || []).concat(desktopDefinition.intents);
1084
+ }
1085
+ return appConfig;
1086
+ }
1087
+ }
1088
+
1089
+ const decoders$1 = {
1090
+ common: {
1091
+ nonEmptyStringDecoder,
1092
+ nonNegativeNumberDecoder
1093
+ },
1094
+ fdc3: {
1095
+ allDefinitionsDecoder,
1096
+ v1DefinitionDecoder,
1097
+ v2DefinitionDecoder
1098
+ }
1099
+ };
1100
+
1101
+ class IoC {
1102
+ constructor() {
1103
+ this._decoders = decoders$1;
1104
+ }
1105
+ get fdc3() {
1106
+ if (!this._fdc3) {
1107
+ this._fdc3 = new FDC3Service().toApi();
1108
+ }
1109
+ return this._fdc3;
1110
+ }
1111
+ get decoders() {
1112
+ return this._decoders;
1113
+ }
1114
+ }
1115
+
1116
+ const ioc = new IoC();
1117
+ const fdc3 = ioc.fdc3;
1118
+ const decoders = ioc.decoders;
1119
+
1120
+ export { decoders, fdc3 };
1121
+ //# sourceMappingURL=utils.es.js.map